MattnDo
MattnDo

Reputation: 444

Iterate over a "grouped" list

Edited after comment.

I have a list of lists that looks like that:

old_list = [['A', 1, 2], ['A', 5, 3], ['A', 3, 2], ['B', 1, 1], ['B', 2, 5], ['C', 3 , 1], ['C', 9, 2]]

and I want my function to iterate over it so the output is a list that groups the numerical values of the inner lists by the group identifier (the letter at index 0). See below example of expected output.

new_list = [[1, 2, 5, 3, 3, 2], [1, 1, 2, 5], [3, 1, 9, 1]]

Upvotes: 0

Views: 608

Answers (1)

schilli
schilli

Reputation: 1848

Using a dict, you could achieve a similar result more easily. Just create a dict and check if the group already exists in it.

If it does not, you add the group and add the latter part of the original list slice item[1:] (this operator creates a new list with the entries from item starting from index 1).

If it does exist, you extend the group with the new values.

    old_list = [['A', 1, 2], ['A', 5, 3], ['A', 3, 2], ['B', 1, 1], ['B', 2, 5], ['C', 3 , 1], ['C', 9, 2]]

new_dict = {}
for item in old_list:
    group = item[0]
    if group not in new_dict:
        new_dict[group] = item[1:]
    else:
        new_dict[group].extend(item[1:])
print(new_dict)

# Output:
{'A': [1, 2, 5, 3, 3, 2], 'B': [1, 1, 2, 5], 'C': [3, 1, 9, 2]}

If you want the list form you asked for in the question, just add the following line at the end.

new_list = [item for group, item in new_dict.items()]
print(new_list)

# Output:
[[1, 2, 5, 3, 3, 2], [1, 1, 2, 5], [3, 1, 9, 2]]

Upvotes: 2

Related Questions