首页 > 解决方案 > 如何根据特定元素获取列表元素的所有组合?

问题描述

我目前正在尝试根据特定元素获取列表元素的所有组合。

我曾尝试使用该itertools.combination方法,但它只是为我提供了列表元素的所有组合。

l = ['it', 'them', 'BMW', 'car']

c = list(itertools.combinations(l, 2))

# Output
[('it', 'them'), ('it', 'BMW'), ('it', 'car'), ('them', 'BMW'), ('them', 'car'), 
('BMW', 'car')]

更具体地说,我想要代词元素与其他非代词元素的所有组合(即特定的选定元素)。所以所需的输出如下:

[('it', 'BMW'), ('it', 'car'), ('them', 'BMW'), ('them', 'car')]

有谁知道我怎么能做到这一点?谢谢你。

编辑

更具体地说,我想您可能会说我很好奇是否itertools.combination有一种机制可以让您选择特定元素并与它们进行组合。

标签: pythonlistcombinations

解决方案


使用itertools.product

In [1]: a = ['it', 'them']

In [2]: b = ['bmw', 'car']

In [3]: from itertools import product

In [4]: list(product(a, b))
Out[4]: [('it', 'bmw'), ('it', 'car'), ('them', 'bmw'), ('them', 'car')]

推荐阅读