【问题标题】:Counting recurrences in a nested list [duplicate]计算嵌套列表中的重复次数[重复]
【发布时间】:2017-10-06 05:02:41
【问题描述】:

我有一个嵌套列表,其中分别包含 2 个姓名和 2 个年龄。我需要编写一个函数来查看列表并计算名称出现的次数。列表如下所示:

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']]

所以这个函数会计算詹姆斯在列表中两次,艾伦两次,其余的名字一次。

【问题讨论】:

  • 我不敢告诉你,你问错地方了。如果你想得到你想要的答案,你最好用你迄今为止尝试过的代码更新你的问题,并告诉我们它的问题。
  • 不清楚您的具体问题是什么。你想写这个函数,但是在什么时候卡住了?您的要求也不清楚。函数应该返回 所有 个名称的计数还是只返回作为参数传入的其中一个名称的计数?

标签: python list count nested


【解决方案1】:

要数数,我建议Counter

>>> from collections import Counter
>>> L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'], ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']]
>>> Counter(name for sub_list in L for name in sub_list[:2])
Counter({'James': 2, 'Alan': 2, 'Phil': 1, 'Bill': 1, 'Hillary': 1, 'Henry': 1})

【讨论】:

  • 这很有帮助 :) 谢谢
【解决方案2】:

此代码有效

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'],
     ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']]
name = 'James'
count = 0
for nested_list in L:
    if name in nested_list:
       count+=1
print count

编辑 1: 如果您不知道要搜索的名称并且想要所有名称的计数,则此代码有效

L = [['James', 'Alan', '20', '19'], ['Alan', 'Henry', '17', '23'],
 ['Bill', 'James', '40', '33'], ['Hillary', 'Phil', '74', '28']]
count_dict = {}

for nested_list in L:
    if nested_list[0] not in count_dict.keys():
       count_dict[nested_list[0]] = 0
    elif nested_list[1] not in count_dict.keys():
       count_dict[nested_list[1]] = 0
    count_dict[nested_list[0]] += 1
    count_dict[nested_list[1]] += 1


for key,value in count_dict.items():
    print 'Name:',key,'Occurrence count',value

【讨论】:

  • 有没有办法让我不必在我的代码中包含“James”?因此,如果列表更大并且我不知道所有名称,它仍然会计算它们。
  • 然后使用字典。因此,当您看到一个新名称时,将其作为键添加到字典中并增加该键的值,即名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2021-12-03
  • 2017-05-10
  • 2021-07-16
  • 1970-01-01
  • 2019-02-04
相关资源
最近更新 更多