python - 如何根据特定元素获取列表元素的所有组合?
问题描述
我目前正在尝试根据特定元素获取列表元素的所有组合。
我曾尝试使用该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')]
推荐阅读
- pine-script - 带有计算或输入错误的 Pine-Script normalize() 和 rescale() 函数?
- apache-flink - 修复 Apache Flink 中的 JobId
- datagrip - Data Grip 和外部文件
- c# - 为什么 Xamarin.Forms 中的 VisualElement ID 显示为字符串但实际上是 GUID?
- java - Java多次下载相同的Blob到pdf文件给md5总是不同的
- reactjs - 响应未定义;无法确定在哪里定义它
- javascript - 一页上的两个选项卡菜单相互冲突
- javascript - 在一定时间后进行变量更改 HTML 5/JavaScript
- python - 如何在 OpenAPI3.0 的参数中定义自由形式对象
- javascript - 我在源代码中看不到网页上的数据,但我可以通过检查元素看到