查找lis中的事件

2024-10-01 04:57:50 发布

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

我试图找到列表中每个索引的最大出现次数。例如,如果索引0中的出现次数有5次“find”,则记录5次,如果索引1有2次“find”,则记录2次。所以索引0和索引1都会得到5,2。你知道吗

a = [{'test': []}, 
     {'test': [{'testing': 'Not', 'Nottesting': 'Yes'}]},
     {'test': [{'testing': 'find', 'Nottesting': 'yes'}]},
     {'test': [{'testing': 'maybe', 'Nottesting': 'yes'},
               {'testing': 'find', 'Nottesting': 'maybe'},
               {'testing': 'find', 'Nottesting': 'haha'},
               {'testing': 'find', 'Nottesting': 'sometimes'},
               {'testing': 'sowell', 'Nottesting': 'some'}]},
     {},
     {}]

有没有办法根据每个列表的最大值打印计数?你知道吗

aa = []
for index, l in enumerate(a):
    count = 0
    find = []
    for trying in l.get("test", []):
        if trying["testing"] == "find":
            count += 1
            print(count)

我试着用建议的方法,但没有用。你知道吗

我的电流输出:

1
1
2
3

预期产量

1
3

Tags: intest列表forcount记录notfind
3条回答

只需向后缩进printing指令,这样它就只能在嵌套循环之后执行,而不是每次出现时都执行。你知道吗

for index, l in enumerate(a):
    count = 0
    find = []

    for trying in l.get("test", []):
        if trying["testing"] == "find":
            count += 1

    if count : print(count)

您正在打印内部循环,您正在增加计数。你需要在外面打印。你知道吗

a = [{'test': []}, {'test': [{'testing': 'Not', 'Nottesting': 'Yes'}]}, {'test': [{'testing': 'find', 'Nottesting': 'yes'}]}, {'test': [{'testing': 'maybe', 'Nottesting': 'yes'}, {'testing': 'find', 'Nottesting': 'maybe'}, {'testing': 'find', 'Nottesting':'haha'}, {'testing': 'find', 'Nottesting': 'sometimes'}, {'testing': 'sowell', 'Nottesting': 'some'}]}, {}, {}]

aa = []
for index, l in enumerate(a):
    count = 0
    find = []
    for trying in l.get("test", []):
        if trying["testing"] == "find":
            count += 1
    if count != 0:
        print(count)

或一个班轮:

print([sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a if sum([1 for x in i.get('test',[]) if x['testing']=='find'])!=0])

输出:

[1, 3]

或两行(可读性更强):

l=[sum([1 for x in i.get('test',[]) if x['testing']=='find']) for i in a]
print(list(filter(None,l)))

输出:

[1, 3]

相关问题 更多 >