[英]list comprehension for nested for loop in python
我編寫了以下 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}')
如果你想要一個 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]]
如果您想要一個包含汽車制造商的團體字典,請執行以下操作:
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.