python - 在检查多个列表并限制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'}]
在这些不同的列表中,值来自另一个列表理解条件,因此它们可能为空,如list2
和list6
。
考虑到所有这些列表,我想取前 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
条件。在标准和性能方面有没有更好的方法来避免像我那样检查列表空条件?感谢您的建议或方向,或代码,我可以解决。
解决方案
选项 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
推荐阅读
- java - 在 Java 中格式化日期时遇到问题
- .net - 如何在 F# 中按长度将 observable 拆分为块
- xslt - 将属性值更改为具有相应属性值的另一个元素的位置
- z3 - 如何在 Z3py 中的约束内生成条件
- html - SCSS:display-flex 将元素堆叠在一起
- c - 从C中的typedef中减去一个值?
- maven - WildFly 返回 404 错误,而同一 Maven 项目在 TomEE 上运行良好
- ios - 切换方向时 AVPlayer 刷新(使用 Firebase Firestore 视频链接)
- android - 什么会导致 jni 引用内存问题?几个详细的问题
- python - 根据混合条件删除 DF 行(熊猫)