gpt4 book ai didi

python:比较这些列表的快速简便方法?

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:08 24 4
gpt4 key购买 nike

我为此编写了一个函数,但我认为它可能非常低效且过于复杂,所以我想问问是否有一种简单的方法可以做到这一点。

给定两个列表列表...

foo = [['one', 1], ['two', 1], ['three', 1]]
bar = [['three', 1], ['four', 1], ['five', 1]]

我需要一个会返回...的函数

final = [['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]

所以它检查第一项是否有任何重叠,将第二项加在一起,然后像上面那样返回最终列表

编辑:

foo/bar[1:] 保证是有序的,但它们可能是这样的......

foo = [['the', 100], ['at', 99], ['for', 32]]
bar = [['mitochondria', 20], ['at', 10], ['you', 9]]

换句话说,它们将是相对随机的单词与降序数字配对。

最佳答案

>>> foo = [['one', 1], ['two', 1], ['three', 1]]
>>> bar = [['three', 1], ['four', 1], ['five', 1]]
>>> from collections import Counter
>>> Counter(dict(foo)) + Counter(dict(bar))
Counter({'three': 2, 'four': 1, 'five': 1, 'two': 1, 'one': 1})

所以

>>> (Counter(dict(foo)) + Counter(dict(bar))).items()
[('four', 1), ('five', 1), ('three', 2), ('two', 1), ('one', 1)]

如果顺序很重要:

>>> from collections import OrderedDict
>>> counter = (Counter(dict(foo)) + Counter(dict(bar)))
>>> order = OrderedDict(foo + bar).keys()
>>> [[k, counter[k]] for k in order]
[['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]

如果项目被收集到一个列表L

>>> foo = [['one', 1], ['two', 1], ['three', 1]]
>>> bar = [['three', 1], ['four', 1], ['five', 1]]
>>> from collections import Counter
>>> from collections import OrderedDict
>>> from itertools import chain
>>> L = [foo, bar]
>>> counter = Counter()
>>> for item in L:
... counter.update(dict(item))
...
>>> order = OrderedDict(chain.from_iterable(L))
>>> [[k, counter[k]] for k in order]
[['one', 1], ['two', 1], ['three', 2], ['four', 1], ['five', 1]]

关于python:比较这些列表的快速简便方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com