首页 > 解决方案 > 在检查多个列表并限制python中的结果时避免if条件

问题描述

我有一个场景,我有多个字典列表。任何列表都可以为空。我想依次遍历所有列表并取前 5 个名称。

例如,

list1 = [{'name': 'user1'}]
list2 = []
list3 = [{'name': 'user2'}, {'name': 'user3'}]
list4 = [{'name': 'user4'}, {'name': 'user5'}, {'name': 'user6'}]
list5 = []
list6 = [{'name': 'user7'}, {'name': 'user8'}]

在这些不同的列表中,值来自另一个列表理解条件,因此它们可能为空,如list2list6

考虑到所有这些列表,我想取前 5 个名字。这个想法是:

final_list = []
list1 = [{'name': 'user1'}]
if list1:
    final_list.append(list1)

list2 = []
if list2:
    final_list.append(list2)

list3 = [{'name': 'user2'}, {'name': 'user3'}]
if list3:
    final_list.append(list3)

list4 = [{'name': 'user4'}, {'name': 'user5'}, {'name': 'user6'}]
if list4:
    final_list.append(list4)

list5 = []
if list5:
    final_list.append(list5)

list6 = [{'name': 'user7'}, {'name': 'user8'}]
if list6:
    final_list.append(list6)

for name in final_list:
    # iterate and get the names and limit the results to 5

但是这个有多个if条件。在标准和性能方面有没有更好的方法来避免像我那样检查列表空条件?感谢您的建议或方向,或代码,我可以解决。

标签: pythonlist

解决方案


选项 1:使用双 for 循环

l = [list1, list2, list3, list4, list5, list6] # Aggregating the lists
names = []                                     # Resulting names
max_names = 5
for lst in l:
    for dic in lst:
        names.append(dic['name'])     # Extract name
        if len(names) == max_names:    
            break                     # done with inner loop, since at limit
    else:
        continue                      # no break in inner loop, so keep going
    break                             # stop outer loop, since break in inner loop
        
print(*names, sep = ', ')
 # Out: user1, user2, user3, user4, user5

选项 2:使用生成器

def fun_gen(*l):
    '''
        Create generator for names in sublists of l
    '''
    for sublist in l:
        for d in sublist:
            yield d['name']
            
# Generator for names
names = fun_gen(list1, list2, list3, list4, list5, list6)

# Print first five
print(*[next(names) for _ in range(5)], sep = ', ')
# Out: user1, user2, user3, user4, user5
  

推荐阅读