繁体   English   中英

如何计算具有 2 个字符串元组的列表中的第一个元素?

[英]How to count the first element in a list with 2-tuples of strings?

我正在尝试定义一个 function count_first_names输入名称列表,字符串的 2 元组,如(first_name,last_name)并返回一个字典,其键是名字,值是名字出现的次数在名单上。

以美国前5任总统为例,

presidents = [("George","Washington"),
              ("John","Adams"),
              ("Thomas","Jefferson"),
              ("James", "Madison"),
              ("James", "Monroe"),]

然后,我想看看:

count_first_names(presidents)
{'George':1, 'John':1, 'Thomas':1, 'James':2}

首先,我创建了一个空字典,并获取列表中每个元组的第一个元素。 但我不确定下一步该做什么。 请帮忙?

要计算多个项目,请使用Counter

collections.Counter(p[0] for p in presidents)
# Counter({'James': 2, 'George': 1, 'John': 1, 'Thomas': 1})

结果是一个dict子类。

试试这个代码:

presidents = [("George","Washington"),
              ("John","Adams"),
              ("Thomas","Jefferson"),
              ("James", "Madison"),
              ("James", "Monroe"),]
count_dict = {}
for ele in presidents:
    count_dict[ele[0]] = count_dict.get(ele[0],0) + 1

print(count_dict)

output 是:

{'George': 1, 'John': 1, 'Thomas': 1, 'James': 2}

如果你想尝试理解:

{firstName:sum(item[0]==firstName for item in presidents) for firstName in set(item[0] for item in presidents)}

OUTPUT

Out[7]: {'Thomas': 1, 'John': 1, 'George': 1, 'James': 2}

暂无
暂无

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

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