所以我有一个列表,列出了人们每次玩游戏是否赢,输还是输:
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
让我知道您将如何解决问题
答案 0 :(得分:2)
您想要的结果不是有效的语法。您最有可能需要字典列表。
collections.Counter
仅对可迭代值进行计数;除非您提供其他逻辑,否则它不计算外部提供的密钥。
在这种情况下,您可以将列表理解与空字典结合使用:
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}]
答案 1 :(得分:1)
我可以使用字典吗?
您可以使用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})]
要为丢失的键添加零计数,可以使用其他循环:
>>> 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})]
或者,您可以用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
答案 2 :(得分:1)
您可以为给定列表中的每个sublist
应用一个列表理解。
还要声明您自己的counter
函数,该函数计算win
,lose
或draw
中一项的外观。 / p>
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}]