python - 连接列表列表中的两个字符串

标签 python

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

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/

相关文章:

python - 热图半球图

python - Pandas 如何确定某个东西是否是 "scalar"?

python - 用pyshark统计包数

python - 尝试使用 2 列

Python:使用 "with"打开压缩或解压缩文件

python distutils 在模块目录中包含 shell 脚本

Python 检查循环中的条件是否改变

python - 如何从 pyplot 中不规则的 xyz 数据创建热图?

python - 单元测试导入失败——缺少符号

python - 如何在不使用for循环的情况下从数组列表中删除元素