Python 中 combinations 的详细用法

生成可迭代对象中所有可能的组合,不考虑顺序:

python 复制代码
from itertools import combinations

combinations(iterable, r)

其中iterable是可迭代对象,如列表元组字符串等

r是每个组合包含的元素个数

如 items = ['A', 'B', 'C', 'D']

复制代码
print(list(combinations(items, 2)))
# 输出: [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
复制代码
print(list(combinations(items, 3)))
# 输出: [('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'D'), ('B', 'C', 'D')]

但是相同的元素会被视为不同的位置:

复制代码
print(list(combinations('AAA', 2))) 
# 输出: [('A', 'A'), ('A', 'A'), ('A', 'A')]

常见用法

1.生成点对

python 复制代码
points = [(1, 2), (3, 4), (5, 6), (7, 8)]

for (x1, y1), (x2, y2) in combinations(points, 2):
    distance = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
    print(f"点({x1},{y1}) 和 点({x2},{y2}) 的距离: {distance:.2f}")

2.与zip结合生成矩阵对:

python 复制代码
# 原始问题中的用法
bottomLeft = [[1, 1], [2, 2], [3, 3]]
topRight = [[4, 4], [5, 5], [6, 6]]

# 将两个列表对应元素配对
rects = list(zip(bottomLeft, topRight))
# rects = [([1, 1], [4, 4]), ([2, 2], [5, 5]), ([3, 3], [6, 6])]

# 生成所有矩形对
for rect1, rect2 in combinations(rects, 2):
    print(f"矩形1: {rect1}, 矩形2: {rect2}")

3.与set结合,获得唯一组合

python 复制代码
data = [1, 2, 2, 3]
unique_combos = set(combinations(sorted(data), 2))
print("唯一组合:", unique_combos)
# 输出: {(1, 2), (1, 3), (2, 2), (2, 3)}

如果考虑排列顺序呢?用permutations

python 复制代码
from itertools import permutations

items = ['A', 'B', 'C']
print(list(permutations(items, 2)))
# 输出: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
相关推荐
张3蜂20 小时前
Python 四大 Web 框架对比解析:FastAPI、Django、Flask 与 Tornado
前端·python·fastapi
qq_124987075320 小时前
基于Java Web的城市花园小区维修管理系统的设计与实现(源码+论文+部署+安装)
java·开发语言·前端·spring boot·spring·毕业设计·计算机毕业设计
2601_9483745721 小时前
商用电子秤怎么选
大数据·python
Volunteer Technology21 小时前
Sentinel的限流算法
java·python·算法
froginwe1121 小时前
Python 条件语句
开发语言
七夜zippoe21 小时前
Python统计分析实战:从描述统计到假设检验的完整指南
开发语言·python·统计分析·置信区间·概率分布
2601_9491465321 小时前
Python语音通知API示例代码汇总:基于Requests库的语音接口调用实战
开发语言·python
去码头整点薯条9821 小时前
python第五次作业
linux·前端·python
3GPP仿真实验室21 小时前
【Matlab源码】6G候选波形:OFDM-IM 索引调制仿真平台
开发语言·matlab
有代理ip21 小时前
Python 与 Golang 爬虫的隐藏优势
爬虫·python·golang