I have a list containing two sublists. I want all the string elements in every sublist to be part of the same sentence. So far I could only remove the commas but the quotation marks stay and additional ones appear on the sides of the squared brackets. In addition, the new 'subbrackets' are now string elements instead of being delimiters of the sublist. This is my code:
l1=['ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO']
l2=['george','sandy','margaret', 'jack']
names=[l1,l2]
b=[]
for i in names:
b.append(( ''.join(str(i).split(','))))
print(b)
This is what it prints
["['ELDEN' 'DORSEY' 'DARELL' 'BRODERICK' 'ALONSO']", "['george' 'sandy' 'margaret' 'jack']"]
but this is what I want to get:
[['ELDEN DORSEY DARELL BRODERICK ALONSO'], ['george sandy margaret jack']]
with the squared brackets inside being actual delimiters of the sublists instead of strings.
CodePudding user response:
The issue is that you convert the sublists to string.
Use a simple list comprehension:
b = [[' '.join(l)] for l in names]
Or with a classical loop:
b = []
for l in names:
b.append(' '.join(l))
Output:
[['ELDEN DORSEY DARELL BRODERICK ALONSO'],
['george sandy margaret jack']]
CodePudding user response:
Used str.join
to concatenate string-like elements of a list. Notice that you should call it with a "white space", ' '.join
.
l1 = ['ELDEN', 'DORSEY', 'DARELL', 'BRODERICK', 'ALONSO']
l2 = ['george','sandy','margaret', 'jack']
l3 = [[' '.join(strings)] for strings in [l1] [l2]]
print(l3)