[英]How do I get all combinations of a list's elements, according to a specific element(s)?
我目前正在嘗試根據特定元素獲取列表元素的所有組合。
我嘗試使用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
是否具有一種機制,您可以選擇特定的元素並與之產生組合。
使用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')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.