在3个列表之间组合元素

2024-09-27 22:38:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下3个列表:

list1 = [a,b,c]
list2=[1,3,5]
list3 =[d,e,f]

我希望输出如下所示: [a1d、a1e、a1f、a3d、a3e、a3f、a5d、a5e、a5f、b1d、b1e、b1f、b3e、b3d、b3f等]

我尝试使用itertools,但没有得到我想要的。请告诉我可以用什么。如combinations between two lists?所述


Tags: 列表list2list1list3a3da1da1ea3e
3条回答

列表1和2不包含字符串,因此它们需要用引号括起来

我还添加了一个映射到字符串以将整数转换为字符串

最终代码应为:

import  itertools
list1 = ["a","b","c"]
list2=[1,3,5]
list3 =["d","e","f"]

print([''.join(map(str,t)) for t in itertools.product(list1, list2, list3)])

这将提供以下输出:

['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']

如果您正在开始编程,一个更容易理解的方法是在两个列表上进行三重循环

list1 = ['a','b','c']
list2=[1,3,5]
list3 =['d','e','f']

res = []

for i1 in list1:
    for i2 in list2:
        for i3 in list3:
            res.append(str(i1) + str(i2) + str(i3)) # "+" operator acts as concatenation with Strings
print(res)

Output : ['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']

也别忘了在你的a,b,c。。。因为有字符(字符串类型)而没有变量

适用于任意数量的列表:

pools = [["a","b","c"], [1,3,5], ["d","e","f"]]
result = [[]]
for pool in pools:
    result = [x+[y] for x in result for y in pool]
result = ["".join([str(x) for x in lst]) for lst in result]

print(result)

输出:

['a1d', 'a1e', 'a1f', 'a3d', 'a3e', 'a3f', 'a5d', 'a5e', 'a5f', 'b1d', 'b1e', 'b1f', 'b3d', 'b3e', 'b3f', 'b5d', 'b5e', 'b5f', 'c1d', 'c1e', 'c1f', 'c3d', 'c3e', 'c3f', 'c5d', 'c5e', 'c5f']

相关问题 更多 >

    热门问题