Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make this python code simpler?

Tags:

python

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.

like image 549
fullmooninu Avatar asked Jan 26 '26 23:01

fullmooninu


2 Answers

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.

like image 58
chepner Avatar answered Jan 28 '26 13:01

chepner


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']):
like image 43
Alexey Larionov Avatar answered Jan 28 '26 13:01

Alexey Larionov