[英]list comprehension for nested for loop in python
I wrote the following for loop, I am looking into converting this into a list comprehension, would appreciate any pointers.我编写了以下 for 循环,我正在考虑将其转换为列表理解,不胜感激。
car_dict = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')}
group_list = ['G1', 'G2', 'G3', 'G4']
for group in group_list:
for car, value in car_dict.items():
for car_group in value:
if car_group in group:
print(f'{car} in {group}')
else:
print(f'{car} not in {group}')
If you want an array of True False you can do the following:如果你想要一个 True False 数组,你可以执行以下操作:
car_dict = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')}
group_list = ['G1', 'G2', 'G3', 'G4']
in_group = [[group in val for key, val in car_dict.items()]
for group in group_list]
print(in_group)
# output
[[True, False, False], [False, True, True], [False, False, True], [False, False, True]]
If you want a dictionary of group with car manufacturers do the following:如果您想要一个包含汽车制造商的团体字典,请执行以下操作:
in_group_names = {group: [key for key, val in car_dict.items() if group in val]
for group in group_list}
print(in_group_names)
# output
{'G1': ['mazda'],
'G2': ['toyota', 'nissan'],
'G3': ['nissan'],
'G4': ['nissan']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.