如何在 Python 中按元素连接两个列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19560044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:03:27  来源:igfitidea点击:

How to concatenate element-wise two lists in Python?

pythonlist

提问by Sanchit

I have two lists and I want to concatenate them element-wise. One of the list is subjected to string-formatting before concatenation.

我有两个列表,我想按元素连接它们。列表之一在连接之前进行字符串格式化。

For example :

例如 :

a = [0, 1, 5, 6, 10, 11] 
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']

In this case, ais subjected to string-formatting. That is, new aor aashould be :

在这种情况下,a受制于字符串格式。也就是说,新的aaa应该是:

aa = [00, 01, 05, 06, 10, 11]

Final output should be :

最终输出应该是:

c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']

Can somebody please tell me how to do that?

有人可以告诉我怎么做吗?

采纳答案by orlp

Use zip:

使用zip

>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']

回答by Edgar Klerks

Than can be done elegantly with map and zip:

可以使用 map 和 zip 优雅地完成:

map(lambda (x,y): x+y, zip(list1, list2))

Example:

例子:

In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7]))
Out[1]: [5, 7, 9, 11]

回答by Vorsprung

not using zip. I dunno, I think this is the obvious way to do it. Maybe I just learnt C first :)

不使用 zip。我不知道,我认为这是显而易见的方法。也许我只是先学了 C :)

c=[]
for i in xrange(len(a)):
    c.append("%s%02d" % (b[i],a[i]))

回答by RMcG

Using zip

使用 zip

[m+str(n) for m,n in zip(b,a)]

output

输出

['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']

回答by MONTYHS

b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
aa = [0, 1, 5, 6, 10, 11]
new_list =[]
if len(aa) != len(b):
     print 'list length mismatch'
else:
    for each in range(0,len(aa)):
        new_list.append(b[each] + str(aa[each]))
print new_list

回答by vaab

Other solution (preferring printf formatingstyle over .format()usage), it's also smaller:

其他解决方案(更喜欢printf 格式样式而不是.format()使用),它也更小:

>>> ["%s%02d" % t for t in zip(b, a)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']

回答by IndPythCoder

inputs:

输入:

a = [0, 1, 5, 6, 10, 11] 
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']

concat_func = lambda x,y: x + "" + str(y)

list(map(concat_func,b,a)) # list the map function

output:

输出:

['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']

回答by Veneet Reddy

If you wanted to concatenate arbitrary number of lists, you could do this:

如果你想连接任意数量的列表,你可以这样做:

In [1]: lists = [["a", "b", "c"], ["m", "n", "o"], ["p", "q", "r"]] # Or more

In [2]: lists
Out[2]: [['a', 'b', 'c'], ['m', 'n', 'o'], ['p', 'q', 'r']]    

In [4]: list(map("".join, zip(*lists)))
Out[4]: ['amp', 'bnq', 'cor']