Python Multiplicative Array连接

时间:2016-09-20 14:55:01

标签: python arrays list

如果我有一个大小不一致的数组,lists包含(不一致)数量的列表:

 lists = [List1, List2, List3,...ListN]

其中每个包含的列表的大小不一致。

如何连接每个包含的数组的内容。

目标输出示例:

A = ["A","B","C","D"]
B = ["1","2","3","4"]
C = ["D","E","F","G"]
A[0-N] + B[0-N] + C[0-N]

Giving ["A1D","B1D","C1D","D1D",
        "A2D","B2D","C2D","D2D"
        "A3D","B3D","C3D","D3D"
        "A4D","B4D","C4D","D4D"
        "A1E","B1E","C1E","D1E"

         ... "C4G","D4G"  ]

对于此特定示例,它应该产生4 ^ 3的列表长度。 (列出长度与列表数量的幂)

但是列表长度不是常数所以它确实是

List1 Length * List2 Length * List3 Length * ... * ListN Length

对于不一致的列表长度:

  A = ["A","B"]
  B = ["1","2","3","4"]

 = ["A1","A2","A3","A4","B1","B2","B3","B4"]

我已经尝试过python地图和拉链,但我在做例如:

zip(list1, list2, list3)

当:

列表数量不一致

列表不是单独存储的,而是整理在一个大的列表中,

且列表大小不一致

在其他SO问题上描述的方法仅解决一致的大小,2列表,情况。在这种情况下,我无法应用这些技术。

3 个答案:

答案 0 :(得分:1)

import itertools
A = ["A","B"]
B = ["1","2","3","4"]
list(itertools.product(A, B))

通用

lists_var = [List1, List2, List3,...ListN]
list(itertools.product(*lists_var))

答案 1 :(得分:1)

使用itertools获取结果,然后根据需要进行格式化:

import itertools

A = ["A","B","C","D"]
B = ["1","2","3","4"]
C = ["D","E","F","G"]

lists = [A, B, C]

results = [''.join(t) for t initertools.product(*lists)]

print(results)

打印:

['A1D', 'A1E', 'A1F', 'A1G', 'A2D', 'A2E', 'A2F', 'A2G', 'A3D', 'A3E', 'A3F', 'A3G', 'A4D', 'A4E', 'A4F', 'A4G', 'B1D', 'B1E', 'B1F', 'B1G', 'B2D', 'B2E', 'B2F', 'B2G', 'B3D', 'B3E', 'B3F', 'B3G', 'B4D', 'B4E', 'B4F', 'B4G', 'C1D', 'C1E', 'C1F', 'C1G', 'C2D', 'C2E', 'C2F', 'C2G', 'C3D', 'C3E', 'C3F', 'C3G', 'C4D', 'C4E', 'C4F', 'C4G', 'D1D', 'D1E', 'D1F', 'D1G', 'D2D', 'D2E', 'D2F', 'D2G', 'D3D', 'D3E', 'D3F', 'D3G', 'D4D', 'D4E', 'D4F', 'D4G']

答案 2 :(得分:0)

itertools.product我想是你在找什么:

>>> import itertools
>>> A = ["A","B"]
>>> B = ["1","2","3","4"]
>>> C = [A,B]
>>> [''.join(i) for i in itertools.product(*C)]
['A1', 'A2', 'A3', 'A4', 'B1', 'B2', 'B3', 'B4']