简体   繁体   中英

Same values in two lists (pairs)

I need to have a list going where I have one list with a load of values between 1 and 8 randomly generated and another list with a load of values between 1 and 8 randomly also. I have managed to do this on my code below:

from random import *
listA = []
listB = []
inp = int(input('Number of values generated'))
for x in range(0,inp):
    num = randint(0,8)
    listA.append(num)
    if num == 0:
        numB = randint(1,8)
    else:
        numB = randint(0,8)
    listB.append(numB)
print(listA)
print(listB)

The value in the first list can't be 0 and the value in the second list can't be zero too on the same trial. I have this already in my code. However this is the problem I have.

[4, 5 , 2, 5 , 1]

[1, 2 , 3, 2 , 4]

In listA, the 5 is produced twice and the 2 below it on the second list is produced twice also. I can't figure out a solution to get these out from my lists, when they create a pair like this.

You can use a helper function as below to generate a unique number that is not in the list and append that to the list.

This should work for you:

def generateUnique(list, start, end):  # Helper Function to generate and return unique number not in list
    num = randint(start, end)
    while num in list:  # loop will keep generating a value, until it is unique in the given list
        num = randint(start, end)
    return num


from random import *
listA = []
listB = []
inp = int(input('Number of values generated'))
for x in range(0,inp):
    num = generateUnique(listA, 0, 8)
    listA.append(num)
    if num == 0:
        numB = generateUnique(listB, 1, 8)
    else:
        numB = generateUnique(listB, 0, 8)
    listB.append(numB)

print(listA)
print(listB)

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM