简体   繁体   中英

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM