我有一个列表列表,其中包含:
animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
我想连接动物表内每个列表中的字符串元素,使其成为单个字符串:
animal = [[1, 'Crocodile, Lion'],[2, 'Eagle, Sparrow'],[3,'Hippo, Platypus, Deer']]
我尝试使用 for 循环来加入它们:
for i in range(len(animal)):
''.join(animal[1:]) #string at index 1 and so on
print(animal)
我收到一个类型错误,提示“TypeError: 序列项 0: 预期的 str 实例,找到列表”。
最佳答案
只需要一个小小的改变,你只是忘记了循环中的索引 i :
animal = [[1, 'Crocodile','Lion'],[2, 'Eagle','Sparrow'],[3, 'Hippo','Platypus','Deer']]
merged_animal = []
for element in animal:
merged_animal.append([element[0], ", ".join(element[1:])])
print(merged_animal)
但是如果您了解列表推导式,最好使用它们,如许多答案所示。
关于python - 连接列表列表中的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49336064/