在python中连接2个列表

2024-09-24 22:32:30 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我所拥有的。我想把这两个列表连接在一起

first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie',
'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour']

last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson',
'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skinner']

for (i, j) in zip(first_name, last_name):
    print (first_name[i] + " " + last_name[j])

但是有一条错误消息说

TypeError: list indices must be integers, not str 

在“打印”语句的行上


Tags: name列表firstlastlisabartottoned
3条回答

可以通过以下方式使用Pythonmap function获得所需的输出:

print(map(lambda f,l: f + " " + l, first_name, last_name))

编辑:在使用索引的情况下,但是通过elemenet迭代更好

两个列表长度相同,因此:

for i in range(len(first_name)):
    print(first_name[i] + " "  + last_name[j])

循环实际上是遍历元素,而不是索引

for (f, l) in zip(first_name, last_name):
    print (f + " " + l)

相关问题 更多 >