gpt4 book ai didi

python - 在列表列表中加入两个字符串

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:23 25 4
gpt4 key购买 nike

我有一个列表列表,其中包含:

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)

但是如果您知道列表推导式,最好使用它们,如许多答案所示。

关于python - 在列表列表中加入两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49336064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com