python - 如何在python列表中的值之间进行组合?

标签 python

这个问题在这里已经有了答案:





Get the cartesian product of a series of lists?

(16 个回答)


4 个月前关闭。




我有 3 个列表:

list1=[1,2,3]
list2=[5,6]
list3=[7,8,9]
我想创建以下输出:
   all_combinations=[[1,5,7],
[1,5,8],
[1,5,9],
[1,6,7],
[1,6,8],
[1,6,9],
[2,5,7],
[2,5,8],
[2,5,9],
[2,6,7],
[2,6,8],
[2,6,9],
[3,5,7],
[3,5,8],
[3,5,9],
[3,6,7],
[3,6,8],
[3,6,9]]
我尝试了 itertools 库的功能
但它们都没有带来正确的结果:
itertools.permutations, itertools.combinations

最佳答案

使用 itertools 以这种方式尝试

list1=[1,2,3]
list2=[5,6]
list3=[7,8,9,0]
from itertools import product
combs = product(list1,list2,list3)
for i in combs:
    print(list(i))

关于python - 如何在python列表中的值之间进行组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67209924/

相关文章:

python - 错误: Failed to enable GUI event loop integration for 'qt' while importing pandas

python - 在 MySQL 中使用 pandas 方法 to_sql 时出现另一个 UnicodeEncodeError

python - 生成排列的所有一步变体

python - 应用循环后原始数据帧没有变化

python - Webdriver 测试 - 将事件/通知推送到测试

python - random.choice 的初学者问题

Python:在numpy数组中左右移动所有大于0的元素

python - 在 Django 中使用 Pillow 压缩图像

使用 dict 在 Pushover 中进行 python 确认

python - 在 Pandas Dataframe 上迭代 Google 分析 API 函数