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')]
相关推荐
Java后端的Ai之路11 小时前
【Python 教程15】-Python和Web
python
冬奇Lab12 小时前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
灰子学技术14 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
二十雨辰14 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码14 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚14 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂14 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
pas13615 小时前
41-parse的实现原理&有限状态机
开发语言·前端·javascript
琹箐15 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
前端摸鱼匠15 小时前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测