简体   繁体   English

python:串联列表中的列表字符串

[英]python: concatenating strings of a list within a list

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 for name in names: names = " ".join(name) print(names)此代码的输出为

white farm house

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'. 您将在每个循环中覆盖名称,因此名称的最后一个值是“白色农舍”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM