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')]
相关推荐
16月6日-晴6 小时前
Java面向对象——接口
java·开发语言
wuyk5556 小时前
107.FreeRTOS 链表深度解析:从原理到面试满分答案
c语言·开发语言·数据结构·stm32·单片机·链表·面试
geovindu7 小时前
CSharp: Wordcloud
开发语言·后端·c#·.net·.netcore·词云
智购科技自动售卖机厂家7 小时前
2026自动售货机库存热力图分析:从设备分布到补货优先级的数据可视化实践~YH
大数据·python·信息可视化
Java小白笔记7 小时前
Java 实现 ZIP 压缩包生成方案
java·开发语言·网络·7-zip
Persistent的粽子!7 小时前
C++:类与对象(一)
开发语言·c++·经验分享·笔记
鹿鹿学长7 小时前
微软把语音转写打到 0.1 美元/小时:5 个月降价 72%,AI 音频进入地板价时代
python·自动化
weixin_440730507 小时前
使用pytest中方法控制执行步骤(test_begin.py、test_end.py,@pytest.mark.run(order=1))
开发语言·python·pytest
小柯南敲键盘7 小时前
跨境电商批量图片翻译与视频字幕翻译,就用跨马AI工具
大数据·人工智能·python·音视频
geovindu8 小时前
CSharp: Command Pattern
开发语言·后端·c#·.net·.netcore·命令模式·行为模式