Python if-else random order

This may sound like a weird question, but carry me ...

I have a dictionary in Python with the following values:

'B': 23.6
'D': 0.6
'F': 35.9
'H': 35.9

I need to do if-else with these values ​​in order to do different things, depending on which one is → 30. The code that I have at the moment corresponds to the lines:

if angles['B'] > 30:
  # Do stuff
elif angles['D'] > 30:
  # Do other stuff
elif angles['F'] > 30:
  # Do different stuf
elif angles['H'] > 30:
  # Do even more different stuff

Now the problem arises when I have two or more values ​​the same (as in the examples above). In this case, I want to randomly select one of them to use. The question is: how to do this in Python? Keep in mind that regardless of the values ​​of the dictionary, nothing (if they are all <30) or only one thing should be done.

+3
source share
4 answers

/:

pairs = angles.iteritems()

, <= 30:

filtered = [(name, value) for name, value in pairs if value > 30]

, -

if filtered:

:

    from random import choice
    name, value = choice(filtered)

update: ...

, . , name.

, . , , - /

def thing1(name, value):
    # do stuff...
def thing2(name, value):
    # do different stuff...

routes = {'A': thing1,
          'B': thing2,
          'C': thing1}

, :

def route(pair):
    name, value = pair
    return routes[name](name, value)

route /, choice, .

result = route(choice(filtered))

.

+11

from random import choice

while angles:
    x = choice(angles.keys()) 
    if angles.pop(x)>30:
        if x == 'B':
            # Do stuff
        elif x == 'D':
            # Do other stuff
        elif x == 'F':
           # Do different stuf
        elif x == 'H':
           # Do even more different stuff
        break
+2

...

def has_gt_30(d):
    for key, value in d.items():
        if value > 30:
            return key
    return False

angle = has_gt_30(angles_dict)
if angle:
    do_stuff(angle)

It will not choose one random case, but it will choose one randomly. If you really want a random one, replace the "return key" with an aggregation of keys that match the criteria and return it. Then use random.choice.

+1
source

you also can:

import random

angles = {'B':23,
'D': 2.6,
'F': 35.9,
'H':35.9
}

keys = angles.keys()

random.shuffle(keys) # shuffle the list of dictionary keys

for key in keys:
   if angles[key] > 30:
      # ...
      break
+1
source

Source: https://habr.com/ru/post/1769820/


All Articles