Home > database >  How to check if random generated number forms a couple in a list of lists PYTHON
How to check if random generated number forms a couple in a list of lists PYTHON

Time:11-16

I have 4 lists of couples of numbers and a list that contains all the 4 lists. I need to create a list with 4 numbers in total, in which only one couple is from the list_couples and the rest are randomly generated (for example:[1,21,5,6]). Does anyone have an idea how to make a condition of checking whether the rest of the randomly generated numbers form a couple that exist in list_couples? (so that i dont get something like this: [1,21,2,22])

list1=[1,21]
list2=[1,31]
list3=[2,12]
list4=[2,22]
list5=[10,20]
list_couples = [list1, list2,list3,list4]

CodePudding user response:

You could check to see if your random couple is in list_couple and loop until it isn't

import random

list1=[1,21]
list2=[1,31]
list3=[2,12]
list4=[2,22]
list5=[10,20]
list_couples = [list1,list2,list3,list4]

rand_couple = [random.randint(1,99), random.randint(1,99)]
#Loop until rand_couple isn't in list_couples
while rand_couple in list_couples:
    rand_couple = [random.randint(1,99), random.randint(1,99)]

print(random.choice(list_couples)   rand_couple)

CodePudding user response:

You can make a simple loop that checks for exactly that.

for i in list_couples:
    if finallist[2] in i or finallsit[3] in i:
        #just replace the number here however you would like

You can now make the function recursive and just check again and again. Not the prettiest answer but i think its easiest to understand for just the concept.

  • Related