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

2024-04-24 11:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一份名单,上面列出了人们每次比赛的胜负:

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

我想得到每个子列表的计数'win'/'lose'/'draw'

我能用字典做这个吗?你知道吗

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

我试着数数,然后把它们放进一个列表:

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

但这只返回了0

告诉我你将如何解决这个问题


Tags: in列表for字典itemwindict计数
3条回答

Can I do this using a dictionary?

您可以使用^{},它是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})]

要为丢失的键添加零计数,可以使用附加循环:

>>> 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})]

或者,可以用^{}包装计数器:

>>> 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

所需结果的语法无效。很可能你想要一个字典列表。你知道吗

collections.Counter只对iterable中的值进行计数;除非提供额外的逻辑,否则不会对外部提供的键进行计数。你知道吗

在这种情况下,您可以使用列表理解,并结合使用空词典:

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}]

您可以对给定列表中的每个sublist应用列表理解。你知道吗

另外,声明您自己的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]

输出

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

相关问题 更多 >