I have a list of tuples of elements like this:
[
('All', 1, 0.6, 5.0),
('right,', 1, 0.6, 5.0),
("let's", 1, 0.6, 5.0),
('get', 0, 0.36, 5.0),
('the', 0, 0.36, 5.0),
('clock', 0, 0.36, 5.0),
('up', 0, 0.36, 5.0),
('here.', 0, 0.36, 5.0)
]
I want to split this list into two lists whenever the 1st element changes. The result should be like this:
[
('All', 1, 0.6, 5.0),
('right,', 1, 0.6, 5.0),
("let's", 1, 0.6, 5.0)
],
[
('get', 0, 0.36, 5.0),
('the', 0, 0.36, 5.0),
('clock', 0, 0.36, 5.0),
('up', 0, 0.36, 5.0),
('here.', 0, 0.36, 5.0)
]
What's the most pythonic way of doing this?
CodePudding user response:
mozway surely beat me but here's a solution that doesn't use libraries. It uses dictionaries!
lst = [...] # contains your list
dct = {}
for tpl in lst:
idx = tpl[1] # idx has the 'dependent' variable
temp = dct.get(idx, [])
temp.append(tpl)
dct[idx] = temp
print(list(dct.values()))
print(dct.keys())
CodePudding user response:
This is a perfect use case for itertools.groupby
:
Assuming the input list as l
:
from itertools import groupby
[list(g) for k,g in groupby(l, lambda x: x[1])]
output:
[[('All', 1, 0.6, 5.0), ('right,', 1, 0.6, 5.0), ("let's", 1, 0.6, 5.0)],
[('get', 0, 0.36, 5.0), ('the', 0, 0.36, 5.0), ('clock', 0, 0.36, 5.0), ('up', 0, 0.36, 5.0), ('here.', 0, 0.36, 5.0)]
]
CodePudding user response:
I used a list comprehension just to make it a single line statement.
Assumed that the entries change are 0 or 1.
lst = [
('All', 1, 0.6, 5.0),
('right,', 1, 0.6, 5.0),
("let's", 1, 0.6, 5.0),
('get', 0, 0.36, 5.0),
('the', 0, 0.36, 5.0),
('clock', 0, 0.36, 5.0),
('up', 0, 0.36, 5.0),
('here.', 0, 0.36, 5.0)
]
new_lst = [[], []]
[new_lst[0].append(i) if i[1] == 0 else new_lst[1].append(i) for i in lst]
print(new_lst)
Output
[[('get', 0, 0.36, 5.0), ('the', 0, 0.36, 5.0), ('clock', 0, 0.36, 5.0), ('up', 0, 0.36, 5.0), ('here.', 0, 0.36, 5.0)], [('All', 1, 0.6, 5.0), ('right,', 1, 0.6, 5.0), ("let's", 1, 0.6, 5.0)]]