问题
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