eljobso eljobso - 5 months ago 11
Python Question

Create nested list of tuple elements based on the string integer number as index

Let’s say I have a tuple, which contains lists, where its first element is always a string-number, e.g.

asdf = (['0', ...], ['1', ...], ['2', ...], ['3.0', ...], ['3.1', ...], ['3.2', ...], ['4', ...] , ['5.0', ...], ['5.1', ...])


Baiscally, I want to have a list, which contains all the string-number of the lists of the tuple.

However, if the first value of each list contains a subindex (in this case
3.0, 3.1, 3.2 and 5.0, 5.1
) I want to put these subvalues together into a sublist. The result in this example should look like the following.

Result = ['0', '1', '2', ['3.0', '3.1', '3.2'], '4', ['5.0', '5.1']]


Thanks for your help.

Answer

Use itertools.groupby,

import operator
import itertools

tuples = (['0', ], ['1', ], ['2', ], ['3.0', ], ['3.1', ], ['3.2', ], ['4', ] , ['5.0', ], ['5.1', ])

l = map(operator.itemgetter(0), tuples)
# ['0', '1', '2', '3.0', '3.1', '3.2', '4', '5.0', '5.1']

results = list()
for name, group in itertools.groupby(l, key=lambda x:x.split('.')[0]):
    tmp_list = list(group)
    results.append(tmp_list[0] if len(tmp_list)==1 else tmp_list)

print(results)
# Output
['0', '1', '2', ['3.0', '3.1', '3.2'], '4', ['5.0', '5.1']]