python中嵌套for循环的列表理解
我为循环写了以下内容,我希望将其转换为列表理解,如果有任何提示,我将不胜感激python中嵌套for循环的列表理解,python,python-3.x,Python,Python 3.x,我为循环写了以下内容,我希望将其转换为列表理解,如果有任何提示,我将不胜感激 car_dict = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')} group_list = ['G1', 'G2', 'G3', 'G4'] 如果需要True False数组,可以执行以下操作: car_dict = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3'
car_dict = {'mazda': ('G1',), 'toyota': ('G2',), 'nissan': ('G3', 'G2', 'G4')}
group_list = ['G1', 'G2', 'G3', 'G4']
如果需要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']}
如果您想了解汽车制造商的集团词典,请执行以下操作:
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']}