简体   繁体   English

计算项目在每个嵌套列表中出现的次数

[英]Count the number of times an item occurs in each nested list

So I have a list of whether or not people won, drew or lost a game over each time they played: 因此,我列出了人们每次玩游戏是否赢,输还是输的列表:

scores = [["win","lose","win"],["win","win"],["draw","win"],["lose"]]

And I want to get a count of 'win' / 'lose' / 'draw' for each sublist 我想为每个子列表计算'win' / 'lose' / 'draw'

Can I do this using a dictionary? 我可以使用字典吗?

eg dict= {[win:2, draw:0, lose:1],[win:2, draw:0, lose:0].....} 例如dict= {[win:2, draw:0, lose:1],[win:2, draw:0, lose:0].....}

I tried counting and placing in a list by doing this: 我尝试通过执行以下操作计数并放置在列表中:

countlose=0
for sublist in scores:
    for item in sublist:
        for item in range(len(sublist)):
            if item=="lose":
                countlose+=1
print(countlose)

But this just returned 0 但这只是返回0

Let me know how you would solve the problem 让我知道您将如何解决问题

Your desired result isn't valid syntax. 您想要的结果是无效的语法。 Most likely you want a list of dictionaries. 您最有可能需要字典列表。

collections.Counter only counts values in an iterable; collections.Counter仅对可迭代值进行计数; it does not count externally supplied keys unless you supply additional logic. 除非您提供其他逻辑,否则它不计算外部提供的密钥。

In this case, you can use a list comprehension, combining with an empty dictionary: 在这种情况下,您可以使用列表推导和空字典:

from collections import Counter

scores = [["win","lose","win"],["win","win"],["draw","win"],["lose"]]

empty = dict.fromkeys(('win', 'lose', 'draw'), 0)

res = [{**empty, **Counter(i)} for i in scores]

[{'draw': 0, 'lose': 1, 'win': 2},
 {'draw': 0, 'lose': 0, 'win': 2},
 {'draw': 1, 'lose': 0, 'win': 1},
 {'draw': 0, 'lose': 1, 'win': 0}]

Can I do this using a dictionary? 我可以使用字典吗?

You can use collections.Counter , which is a subclass of dict for counting hashable objects: 您可以使用collections.Counter ,它是dict的子类,用于计算可哈希对象:

>>> from collections import Counter
>>> scores = [['win', 'lose', 'win'], ['win', 'win'], ['draw', 'win'], ['lose']]
>>> counts = [Counter(score) for score in scores]
>>> counts
[Counter({'win': 2, 'lose': 1}), Counter({'win': 2}), Counter({'draw': 1, 'win': 1}), Counter({'lose': 1})]

To add zero counts for missing keys you can use an additional loop: 要为丢失的键添加零计数,可以使用其他循环:

>>> for c in counts:
...     for k in ('win', 'lose', 'draw'):
...         c[k] = c.get(k, 0)
... 
>>> counts
[Counter({'win': 2, 'lose': 1, 'draw': 0}), Counter({'win': 2, 'lose': 0, 'draw': 0}), Counter({'draw': 1, 'win': 1, 'lose': 0}), Counter({'lose': 1, 'win': 0, 'draw': 0})]

Alternatively, you could wrap the counters with collections.defaultdict : 或者,您可以使用collections.defaultdict将计数器包装起来:

>>> counts = [defaultdict(int, Counter(score)) for score in scores]
>>> counts
[defaultdict(<class 'int'>, {'win': 2, 'lose': 1}), defaultdict(<class 'int'>, {'win': 2}), defaultdict(<class 'int'>, {'draw': 1, 'win': 1}), defaultdict(<class 'int'>, {'lose': 1})]
>>> counts[0]['draw']
0

You could apply a list comprehension for every sublist from your given list. 您可以对给定列表中的每个sublist应用列表理解

Also, declare your own counter function which counts the number of appearances of one item from win , lose or draw . 另外,声明您自己的counter函数,该函数计算winlosedraw的一项出现的次数。

scores = [["win","lose","win"],["win","win"],["draw","win"],["lose"]]
def get_number(sublist):
  counter = {'win': 0, 'draw' : 0, 'lose': 0}
  for item in sublist:
    counter[item] += 1
  return counter

result = [get_number(sublist) for sublist in scores]

Output 产量

[{'win': 2, 'draw': 0, 'lose': 1}, 
 {'win': 2, 'draw': 0, 'lose': 0}, 
 {'win': 1, 'draw': 1, 'lose': 0}, 
 {'win': 0, 'draw': 0, 'lose': 1}]

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

相关问题 如何计算项目在另一个列表的列表中出现的次数 - How to count the number of times an item occurs in a list base on another list 计算列表中每个项目在 Pandas 数据框列中出现的次数,用逗号将值与其他列的附加聚合分开 - Count number of times each item in list occurs in a pandas dataframe column with comma separates values with additional aggregation of other columns Python | 返回项目在列表中出现的次数 - Python | Return the number of times the item occurs in the list 如何列出每个项目出现不同次数的列表? - How do I make a list where each item occurs a different number of times? 计算每个项目在字典中出现的次数 - count how many times each item occurs in a dictionary 使用递归Python计算项目在序列中出现的次数 - Count the number of times an item occurs in a sequence using recursion Python 计算每个值在pandas列中出现的次数 - Count number of times each value occurs in pandas column 如何使用.count计算一个列表中每个项目出现在python中另一个列表中的次数? - How to use .count to calculate number of times each item in one list appears in another list in python? 计算列表中每个项目的出现次数 - Count number of occurrences for each item in a list 计算嵌套列表中每个位置的出现次数 - Count number of occurences for each position in nested list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM