python - Python all combinations of one item per list
问题描述
I have a varying number of lists of varying length. I need to try to create all possibilities of having one item per list. How can this be done in Python?
Example
l1 = ['a', 'b', 'c']
l2 = [1, 2]
l3 = [6]
# Expected result:
[
['a', 1, 6],
['a', 2, 6],
['b', 1, 6],
['b', 2, 6],
['c', 1, 6],
['c', 2, 6],
]
I could have 3 loops in this case, but since this is for an ambiguous number of lists it doesn't scale.
I tried playing with itertools a bit but couldn't figure out what to use for my case and couldn't find similar questions here. So any help would be appreciated.
解决方案
If you have a varying number of lists, you should use a list of lists, not separate variables. Then you can spread the list into arguments to itertools.product()
.
import itertools
lists = [
['a', 'b', 'c'],
[1, 2],
[6]
]
print(list(itertools.product(*lists)))
推荐阅读
- angular - Angular 8 .NET Core 3.0.CORS 在某些请求中出现错误,但在其他请求中没有
- node.js - 如何将常量值与 api get 请求一起发送到节点服务器
- laravel - 将 Three.js 与 Laravel 一起使用 - 未定义要求
- mongodb - Mongo shell 似乎停止了脚本
- react-native - 反应本机错误 - 期望一个字符串或一个类但得到对象
- node.js - tabris.js websocket只能接收字符串
- react-native - 从选项卡导航选项卡打开抽屉导航
- python - 如何使用 python 提交对 google-forms 的响应?
- azure - 如何让 Azure 应用服务信任 OnPrem CA 颁发的证书?
- javascript - useMutation 总是返回未定义的数据