我有一个列表列表,其中包含:
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 实例,已找到列表”。
只需要一个小改动,你只是忘记了循环中的索引:
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)
但是如果您知道列表推导式,最好使用它们,如许多答案所示。
我是一名优秀的程序员,十分优秀!