Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中嵌套for循环的列表理解_Python_Python 3.x - Fatal编程技术网

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']}