python: concatenating strings of a list within a list

[亡魂溺海] 提交于 2021-02-05 11:16:25

问题


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']]

Expected output below:

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

Here is what I have tried

for name in names: names = " ".join(name) print(names) the output of this code is

white farm house

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


回答1:


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

Try this instead:

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

Output:

['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)

Output:

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


来源:https://stackoverflow.com/questions/54988788/python-concatenating-strings-of-a-list-within-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!