gl00ten
gl00ten

Reputation: 1121

Is there any way to make this python code simpler?

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.

Upvotes: 2

Views: 103

Answers (4)

will f
will f

Reputation: 483

Here is a possible solution without looping/comprehension syntax:

from itertools import product


if any(
  map(
    lambda d,k: d[k] in (4,5),
    product(
      (pop0_dict, …, popN_dict),
      ("max_value0_index", …, "max_valueN_index")
    )
  )
):
  …

Just have to tune the dictionary and key tuples in the product function to suit your actual needs.

Upvotes: 1

chepner
chepner

Reputation: 530940

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.

Upvotes: 15

kelkka
kelkka

Reputation: 1004

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.

Upvotes: 1

Alexey S. Larionov
Alexey S. Larionov

Reputation: 7927

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']):

Upvotes: 2

Related Questions