在两个列表中的相同索引处连接字符串

时间:2015-12-01 21:09:50

标签: python string list python-2.7

我有两个列表,我想按照相同的顺序组合它们。

以下是问题。

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

获取新列表,例如下面的

A+B = ['1,2,3,10','4,5,6,11','7,8,9,12']

我尝试extendzipappendenumerate但无法获得我想要的内容。两个循环结果将重复。

有任何提示或优雅的方法吗?

8 个答案:

答案 0 :(得分:6)

AB是字符串列表。使用zip,您可以创建('1,2,3', '10')之类的对。之后,您可以使用join组合这两个字符串。

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

C = [','.join(z) for z in zip(A, B)]
print C

答案 1 :(得分:5)

只需使用','.joinzip ..

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

C = [ ','.join(pair) for pair in zip(A,B) ]

答案 2 :(得分:4)

[a + ',' + b for a, b in zip(A, B)]

答案 3 :(得分:2)

您当然可以使用enumerate,但zip是更自然的选择

>>> A = ['1,2,3','4,5,6','7,8,9']
>>> B = ['10','11','12']
>>> [a + "," + B[i] for i, a in enumerate(A)]
['1,2,3,10', '4,5,6,11', '7,8,9,12']

答案 4 :(得分:2)

已经回答了,所以这里有一些有趣的游戏 - 如果A和B的长度不同,它们会起作用--zip会留下无与伦比的东西:

>>> A = ['1,2,3','4,5,6','7,8,9']
>>> B = ['10','11','12']

# basic solution using for/len, will except if len(A) > len(B)
>>> [ A[i] + "," + B[i] for i in range(len(A)) ]

# complicated solution to deal with a difference in the
# lengths of A and B 
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12']

# add something to A, len(A) > len(B)
>>> A.append('13,14,15')
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12', '13,14,15,']

# add a couple of things to B, len(B) > len(A)
>>> B.append('16')
>>> B.append('17')
>>> [ (A[i] if i < len(A) else ',,') + "," + (B[i] if i < len(B) else '') for i in range((len(A) if len(A)>=len(B) else len(B))) ]
['1,2,3,10', '4,5,6,11', '7,8,9,12', '13,14,15,16', ',,,17']

答案 5 :(得分:2)

压缩后你也可以map str.join

A = ['1,2,3','4,5,6','7,8,9']
B = ['10','11','12']

from itertools import izip

print(map(",".join, izip(A, B)))
['1,2,3,10', '4,5,6,11', '7,8,9,12']

答案 6 :(得分:2)

假设两个列表的长度相同,那么这个怎么样:

def concat_lists(l1, l2):
    concat_list = []
    for i in range(len(l1)):
        concat_list.append(l1[i] + ',' + l2[i])
    return concat_list

或者改为使用列表理解:

def concat_lists(l1, l2):
    return [l1[i] + ',' + l2[i] for i in range(len(l1))]

答案 7 :(得分:1)

使用map ...当然这种方法不会像list那样创建任何额外的tuples zip ..

>>> A = ['1,2,3','4,5,6','7,8,9']
>>> B = ['10','11','12']
>>> map(lambda x, y:x + ',' + y, A, B)
['1,2,3,10', '4,5,6,11', '7,8,9,12']