Home > Back-end >  Is there any way to make this python code simpler?
Is there any way to make this python code simpler?

Time:05-04

if pop0_dict['max_value1_index'] in (4,5) or pop0_dict['max_value2_index'] in (4,5) or \
    pop1_dict['max_value1_index'] in (4,5) or pop1_dict['max_value2_index'] in (4,5) or \
    pop2_dict['max_value1_index'] in (4,5) or pop2_dict['max_value2_index'] in (4,5) or \
    pop3_dict['max_value1_index'] in (4,5) or pop3_dict['max_value2_index'] in (4,5) or \
    pop4_dict['max_value1_index'] in (4,5) or pop4_dict['max_value2_index'] in (4,5) or \
    pop5_dict['max_value1_index'] in (4,5) or pop5_dict['max_value2_index'] in (4,5):

It seems very much repeated, so I was wondering if there's any way to make it simpler, albeit still readable.

CodePudding user response:

Use any:

dicts = [pop0_dict, pop1_dict, pop2_dict, pop3_dict, pop4_dict, pop5_dict]
indices = ['max_value1_index', 'max_value2_index']
if any(d[i] in (4,5) for d in dicts for i in indices):
    ...

The argument to any is a generator expression, which lazily produces values as the consumer (any) asks for them. As soon as any finds a True value, it returns True, allowing you to avoid performing additional unnecessary containment checks.

CodePudding user response:

You can try this, but you better make a list with dictionaries, instead of having separate variables pop0_dict, pop1_dict, pop2_dict, pop3_dict, pop4_dict, pop5_dict:

if any(d[k] in (4,5) for d in [pop0_dict, pop1_dict, pop2_dict, pop3_dict, pop4_dict, pop5_dict] for k in ['max_value1_index', 'max_value2_index']):

CodePudding user response:

list_of_dicts = [pop0_dict, pop1_dict, pop2_dict, pop3_dict, pop4_dict, pop5_dict]

for dict_inst in list_of_dicts:
    if dict_inst['max_value1_index'] in (4,5) or dict_inst['max_value2_index'] in (4,5):
        # do something

and if you need to add more dictionaries, you can just write a function to populate list_of_dicts.

  • Related