I have a huge python list as the following example:
JavaScript
x
2
1
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
2
I would like to join this information in this formatting:
JavaScript
1
2
1
ls = ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellow cars.']
2
I have tried this code
JavaScript
1
6
1
with open ('names.txt', 'r') as text:
2
lines = text.readlines()
3
for index,line in enumerate(lines):
4
if not linha.startswith('name:'):
5
ls2.append(lines[index]+lines[index+1])
6
But it was not good, since I have something like:
JavaScript
1
2
1
ls = ['name: John', 'John has 4 yellow', '4 yellow cars.', 'cars.name: Angelina']
2
Do you have any idea how can I perform this task?
Advertisement
Answer
You can use itertools.groupby
:
JavaScript
1
8
1
import itertools
2
3
ls = ['name: John', 'John has ', '4 yellow ', 'cars.', 'name: Angelina', 'Angelina has ', '5 yellow', 'cars.']
4
5
g = itertools.groupby(ls, lambda x: x.startswith('name: '))
6
output = [''.join(v) for _, v in g]
7
print(output) # ['name: John', 'John has 4 yellow cars.', 'name: Angelina', 'Angelina has 5 yellowcars.']
8
It groups the items by whether each item starts with 'name: '
;
- Items that start with
'name: '
form a group (i.e.,['name: John']
). - Next a few items that don’t do so form a group (i.e.,
['John has ', '4 yellow ', 'cars.']
). - Next items that do so form another group (
['name: Angelina']
). - … and so on alternatingly.
Then join
concatenates the strings in each group.