我想循环字典列表,并将每个.keys()的.values()与指定的字符串匹配。
例如,
a = [[{'test': 'find', 'another':'trying'}],
[{'test': 'find'},
{'test': 'find'}]]
if .values() == "find"
这里将计数1〜“查找”的总数。最后,打印每个列表的最终计数。
它将获取所有具有“查找”值的.values()值,然后计算出现次数,然后打印出来。
我的代码:
count = 0
for x in a:
for xx in x:
if xx["test"] == "find":
count += 1
print(count)
当前输出:
1 3
我的预期输出:
1 2
说明:
列表[列表[区]]
用于列表中的x时,它将在列表中循环列表。所以我们有List [Dict]
该示例在一个列表中包含2个列表。索引是0和1。索引0仅包含1个“查找”,因此计数将变为1。索引1包含2个“查找”,因此它将1和2作为计数,但是我想获取它的最大值是2。**如果索引1中有5,则计数将是1〜5,因此5是我的最大计数***
有没有办法做到这一点?
答案 0 :(得分:1)
重置每个子列表的计数:
max_count = 0 # initialize max here
for x in a:
count = 0 # reset count here!
for xx in x:
if xx["test"] == "find":
count += 1
if count > max_count:
max_count = count
print(count)
print(max_count)
或更短:
max_count = max(sum(xx['test'] == 'find' for xx in x) for x in a)
答案 1 :(得分:1)
结合使用列表理解和格式的印刷品和.count()
lst = [[j['test'] for j in i] for i in a]
print('{} {}'.format(lst[0].count('find'), lst[1].count('find')))
# 1 2