python:串联列表中的列表字符串 [英] python: concatenating strings of a list within a list

查看:71
本文介绍了python:串联列表中的列表字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从每个列表中获取每个单独的字符串,然后将其组合为一个字符串,然后获得一个字符串列表?而不是列表中的字符串列表?

Is it possible to take each separate string from each list and combine it into one string, then have a list of strings? Instead of a list of strings within a list?

names = ['red','barn'],['barn'],['front','porch'],['white','farm','house']]

下面的预期输出:

名称= ['红色谷仓','谷仓','前廊','白色农舍']

这是我尝试过的

用于名称中的名称:名称=" .join(名称)打印(姓名)此代码的输出是

白色农舍

这为什么只连接列表中的最后一个元素?

Why does this only concatenate the last element in the list?

推荐答案

您正在覆盖每个循环的名称,因此名称的最后一个值是白色农舍".

You are overwriting names each loop, hence the last value of names is 'white farm house'.

尝试以下方法:

l_out = [' '.join(x) for x in names]
print(l_out)

输出:

['red barn', 'barn', 'front porch', 'white farm house']

或者您可以按照尝试的方式进行操作:

Or you can do it the way you're trying:

l_out = []
for name in names:
    l_out.append(' '.join(name))
print(l_out)

输出:

['red barn', 'barn', 'front porch', 'white farm house']

这篇关于python:串联列表中的列表字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆