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')]
相关推荐
独自归家的兔1 小时前
Java性能优化实战:从基础调优到系统效率倍增 -2
java·开发语言·性能优化
开开心心就好2 小时前
内存清理工具开源免费,自动优化清理项
linux·运维·服务器·python·django·pdf·1024程序员节
独自归家的兔2 小时前
Java性能优化实战:从基础调优到系统效率倍增 - 1
java·开发语言·性能优化
小π军2 小时前
C++ STL:array容器常见用法
开发语言·c++
浔川python社2 小时前
浔川AI翻译v6.1.0版本正式发布 全面升级安全体验与交互效率
python
156082072192 小时前
在QT下添加QWT6.1.4功能
开发语言·qt
开开心心_Every2 小时前
图片批量压缩工具:支持有损无损两种模式
python·游戏·微信·django·pdf·excel·语音识别
GIS之路2 小时前
ArcGIS Pro 实现影像波段合成
前端·python·信息可视化
edisao2 小时前
二。星链真正危险的地方,不在天上,而在网络底层
大数据·网络·人工智能·python·科技·机器学习