繁体   English   中英

将列表与元组进行比较

[英]Comparing a list to a tuple

寻找这样做的最佳方式:

所以我有一个包含unicode字符串的列表,让我们调用这个listA

我有一个元组列表,每个元组包含一个unicode字符串和一个整数,让我们调用这个listB

我需要做的是在listB的元组中找到listA中的每个字符串。 如果找到它,则递增该元组中的整数。

通过创建一个新的元组列表,我可以想到很多方法,但我不相信这是最好的方法。

感激地收到任何帮助

您应该使用collections.Counter

>>> from collections import Counter
>>> listA = ['a', 'b', 'c', 'a', 'c']
>>> listB = [('a', 5), ('b', 10), ('c', 0)]

首先将listB转换为Counter对象:

>>> c = Counter(dict(listB))
>>> c
Counter({'b': 10, 'a': 5, 'c': 0})

现在用listA的count来更新它:

>>> c.update(listA)
>>> c
Counter({'b': 11, 'a': 7, 'c': 2})

使用collections.Counter,你会得到结果为字典:

from collections import Counter
txt = """Looking for the best way of doing this: 
    So i have a list containing unicode strings, lets call this listA I 
    have a list of tuples, each of the tuples contains a unicoe string 
    and an integer...
""".split() # this gives list of words

counter = Counter(txt)
for word, count in counter.items():
    print "{}: {}".format(word, count)

实际上, counter.items()为你提供了所需的元组。 计数器给你更多,尝试像counter.most_common()[:10]类的东西,玩得开心。

[编辑]当然以后您可以使用counter.update(another_list_of_words)增加值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM