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')]
相关推荐
@HNUSTer10 分钟前
基于 Visual Studio Code 配置 Python 开发环境详细教程
ide·vscode·python·csdn开发云
tuotali202637 分钟前
天然气压缩机技术2026,高可靠性长周期运行与智能运维融合路径
运维·python
We་ct39 分钟前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
格林威40 分钟前
工业相机图像高速存储(C#版):内存映射文件方法,附Basler相机C#实战代码!
开发语言·人工智能·数码相机·c#·机器视觉·工业相机·堡盟相机
Nuopiane41 分钟前
MyPal3(3)
java·开发语言
Ama_tor41 分钟前
Flask零基础进阶(中)
后端·python·flask
love530love43 分钟前
Windows 11 源码编译 vLLM 0.16 完全指南(RTX 3090 / CUDA 12.8 / PyTorch 2.7.1)
人工智能·pytorch·windows·python·深度学习·vllm·vs 2022
lihihi44 分钟前
P1650 [ICPC 2004 Shanghai R] 田忌赛马(同洛谷2587)
开发语言·算法·r语言
进击的小头44 分钟前
第3篇:最优控制理论数学基础——矩阵与向量的导数
python·线性代数·机器学习·矩阵
浩瀚之水_csdn1 小时前
Flask 深度解析:从微内核到企业级架构
python·架构·flask