Jeremy Jeremy - 1 year ago 74
Python Question

python Combining items in a list of lists based on contents

I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:

[4, 'blue', 'round', None],
[6, 'blue', 'round', None],
[8, 'red', 'round', None],
[10, 'red', 'round', None],
[8, 'red', 'square', None],

I think making a new list might help but am not sure. I need the end product to be:

[10, 'blue', 'round', None],
[18, 'red', 'round', None],
[8, 'red', 'square', None],

The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.

2ps 2ps
Answer Source

Roughly speaking, all you are doing is associating element 0 with a tuple defined as the last three elements of any given list. Luckily, it's perfectly okay for a tuple to be a key of a dictionary!

from collections import OrderedDict
color_data = [[4,'blue','round','none'], [6,'blue','round','none'], [8,'red','round','none'], [10,'red','round','none'], [8,'red','square','none']]
data = OrderedDict()
for x in color_data:
    key = tuple(x[1:])
    value = data.setdefault(key, 0) + x[0]
    data[key] = value
color_data = [ [ value] + list(key) for key, value in data.items() ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download