简体   繁体   English

在 3 个列表之间组合元素

[英]making combination of element between 3 lists

I have 3 lists as below:我有 3 个列表如下:

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

I want output like below: [a1d,a1e,a1f,a3d,a3e,a3f,a5d,a5e,a5f,b1d,b1e,b1f,b3e,b3d,b3f and so on]我想要如下所示的 output:[a1d,a1e,a1f,a3d,a3e,a3f,a5d,a5e,a5f,b1d,b1e,b1f,b3e,b3d,b3f 等等]

I tried using itertools but not getting what I want.我尝试使用 itertools 但没有得到我想要的。 Please tell what can be used.请告诉可以使用什么。 As mentioned in combinations between two lists?两个列表之间的组合所述?

list 1 and 2 do not contain strings, so they need to be enclosed with quotation marks.列表 1 和 2 不包含字符串,因此需要用引号括起来。

I've also added a map to string to convert the ints to string.我还在字符串中添加了一个 map 以将整数转换为字符串。

The final code should be:最终代码应该是:

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)])

This gives the following output:这给出以下 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']

An easier way to understand it if you're starting programming is triple loop on both of your lists.如果您开始编程,一种更容易理解的方法是在您的两个列表上进行三重循环。

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']

Also don't forget to put quotes (simple or double) between your a, b, c, ... since there are characters (String types) and not variables也不要忘记在 a、b、c 之间加上引号(单引号或双引号),因为有字符(字符串类型)而不是变量

Works with any number of lists:适用于任意数量的列表:

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)

out:出去:

['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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM