python: fast and easy way to compare these lists? -
i wrote function this, think wildly inefficient , over-complicated wanted ask if there easy way it.
given 2 lists of lists...
foo = [['one', 1], ['two', 1], ['three', 1]] bar = [['three', 1], ['four', 1], ['five', 1]]
i need function return...
final = [['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]
so checks if there overlaps of first term, adds second terms , returns final list above
edit:
foo/bar[1:] guaranteed ordered, this...
foo = [['the', 100], ['at', 99], ['for', 32]] bar = [['mitochondria', 20], ['at', 10], ['you', 9]]
in other words, relatively random words paired descending numbers.
>>> foo = [['one', 1], ['two', 1], ['three', 1]] >>> bar = [['three', 1], ['four', 1], ['five', 1]] >>> collections import counter >>> counter(dict(foo)) + counter(dict(bar)) counter({'three': 2, 'four': 1, 'five': 1, 'two': 1, 'one': 1})
so
>>> (counter(dict(foo)) + counter(dict(bar))).items() [('four', 1), ('five', 1), ('three', 2), ('two', 1), ('one', 1)]
if order important:
>>> collections import ordereddict >>> counter = (counter(dict(foo)) + counter(dict(bar))) >>> order = ordereddict(foo + bar).keys() >>> [[k, counter[k]] k in order] [['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]
if items gathered list l
>>> foo = [['one', 1], ['two', 1], ['three', 1]] >>> bar = [['three', 1], ['four', 1], ['five', 1]] >>> collections import counter >>> collections import ordereddict >>> itertools import chain >>> l = [foo, bar] >>> counter = counter() >>> item in l: ... counter.update(dict(item)) ... >>> order = ordereddict(chain.from_iterable(l)) >>> [[k, counter[k]] k in order] [['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]
Comments
Post a Comment