Python List Questions ['a', 5', ['e', 5], ['c', 3], ['d', 3], ['e', 1] --> ['a','b', 5', ['c','d', 3], ['b', 1]

Asked 2 years ago, Updated 2 years ago, 35 views

list=['a',5',['e',5],['c',3],['d',3],['e',1]] How do you tie the same numbers together? For example, ['a','b',5],['c','d',3],['b',1]] in the above case. Even if I try for and if, it doesn't come out the way I want, so I can't get a sense of it. Please help me

list python

2022-09-21 09:59

1 Answers

from itertools import groupby
>>> l = [['a',5], ['e',5], ['c',3], ['d',3],['e',1]]
for k, v in groupby(l, lambda x: x[1]):
...    ...    print([a for a, _ in v] + [k])
...
['a', 'e', 5]
['c', 'd', 3]
['e', 1]

pythonbuilt-inmodule has many good functions.
I recommend you take a look at what's there.


2022-09-21 09:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.