from itertools import combinations
# 示例列表
items = ['apple', 'banana', 'cherry', 'date']
# 生成所有长度为2的组合
comb = list(combinations(items, 2))
# 打印组合结果
print(comb)
combinations 是 Python 标准库 itertools 模块中的一个函数,用于生成给定序列的所有可能组合。combinations(items, r) 函数会返回一个迭代器,其中包含从 items 中选择 r 个元素的所有组合。items,并使用 combinations(items, 2) 来生成所有长度为 2 的组合。输出结果将是:
[('apple', 'banana'), ('apple', 'cherry'), ('apple', 'date'), ('banana', 'cherry'), ('banana', 'date'), ('cherry', 'date')]
上一篇:python heapify
下一篇:python cookie
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站