Python-将两个元组列表合并为一个元组列表
什么是pythonic方法来实现以下目标 发件人: 得到Python-将两个元组列表合并为一个元组列表,python,list,Python,List,什么是pythonic方法来实现以下目标 发件人: 得到 c = [('orange', 10), ('of', 17), ('apple', 10)] 基本上有单词计数器对。使用collections.Counter()可以以一种自然、通俗的方式处理这些内容: from collections import Counter c = (Counter(dict(a)) + Counter(dict(b))).items() 也看到 演示: 您只需停止调用.items()并在此处继续使用计数
c = [('orange', 10), ('of', 17), ('apple', 10)]
基本上有单词计数器对。使用
collections.Counter()
可以以一种自然、通俗的方式处理这些内容:
from collections import Counter
c = (Counter(dict(a)) + Counter(dict(b))).items()
也看到
演示:
您只需停止调用.items()
并在此处继续使用计数器()
您可能希望从一开始就避免构建(word,count)元组来处理Counter()
对象。您基本上拥有单词计数器对。使用collections.Counter()
可以以一种自然、通俗的方式处理这些内容:
from collections import Counter
c = (Counter(dict(a)) + Counter(dict(b))).items()
也看到
演示:
您只需停止调用.items()
并在此处继续使用计数器()
您可能希望避免构建(word,count)元组来开始和使用Counter()
从一开始就是对象。使用collections.Counter
你有没有一种非音速的方法来开始呢?使用collections.Counter
你有没有一种非音速的方法来开始呢?有没有避免中间字典的好方法?我也想不出一个…@dhke:没有“好”的方法,它是将(单词,计数)元组列表转换为计数器的最简洁的方法,我想的计数器.update()
但实际上其行为与dict.update()不同
当传递一个元组序列时。有没有避免中间字典的好方法?我也想不出一个…@dhke:没有“好”的方法,它是将(单词,计数)元组列表转换为计数器的最简洁的方法,我一直在想Counter.update()
但是当传递元组序列时,它的行为实际上不同于dict.update()
。
>>> from collections import Counter
>>> a = [('apple', 10), ('of', 10)]
>>> b = [('orange', 10), ('of', 7)]
>>> Counter(dict(a)) + Counter(dict(b))
Counter({'of': 17, 'orange': 10, 'apple': 10})
>>> (Counter(dict(a)) + Counter(dict(b))).items()
[('orange', 10), ('of', 17), ('apple', 10)]