元素明智的concat与Python中的两个列表列表

时间:2020-01-22 08:03:19

标签: python python-3.x list concatenation

我有2个列表列表:

a = [['Apple'], ['Banana']]
b = [[1,2,3,4], [4,5,6]]

如何明智地将其串联为字符串元素,并获得如下所示的新列表列表:

new_list = [['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

最好的问候。

4 个答案:

答案 0 :(得分:4)

使用itertools.cycle

例如:

from itertools import cycle

a = [['Apple'], ['Banana']] 
b = [[1,2,3,4], [4,5,6]]

result = [[m+str(n) for m, n in zip(cycle(i), j) ] for i,j in zip(a, b)]
print(result)

输出:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

答案 1 :(得分:2)

没有itertools的一个:

[["%s%s" % (i[0], n) for n in j] for i,j in zip(a,b)]

输出:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

答案 2 :(得分:1)

这可以帮助您吗?

a = [['Apple'], ['Banana']]
b = [[1,2,3,4], [4,5,6]]
print([
    [c + str(d) for d in j for c in i] for i, j in zip(a, b)
])

输出:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]

答案 3 :(得分:1)

您可以使用2个@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$", 循环:

for

输出:

new_list = []
for [item], numbers in zip(a, b):
    item_list = []
    for n in numbers:
        item_list.append(f'{item}{n}')
    new_list.append(item_list)

new_list

或者您可以使用列表理解:

[['Apple1', 'Apple2', 'Apple3', 'Apple4'], ['Banana4', 'Banana5', 'Banana6']]