PharmDataSci
PharmDataSci

Reputation: 117

How to select a result at random when looping through a list with two matches

I am looping through a list of tuples and I want to add a conditional so that if the condition has multiple successes only one of them is chosen with an equal percentage of chance.

In [1]:
junctions = ([1,2], [1,3], [2,3])
roads = ("a", "b", "c", "d")
for a, b in junctions:
  if a == 1:
    print(roads[b])
Out [1]:
c
d

In this example, I would want it to return either c or d with a 50% chance. Is this possible?

Upvotes: 0

Views: 53

Answers (2)

Llione
Llione

Reputation: 49

You could append these to a new list, and use random.randint() to pick from the size of the new list

import random
sampleList = []
x = random.randint(0,len(sampleList))
print(sampleList[x])

Upvotes: -1

lenik
lenik

Reputation: 23508

You may try this:

from random import choice

possibilities = []
junctions = ([1,2], [1,3], [2,3])
roads = ("a", "b", "c", "d")
for a, b in junctions:
  if a == 1:
     possibilities.append(roads[b])

print(choice(possibilities))

Upvotes: 3

Related Questions