[英]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. 我需要一个列表,其中一个列表随机生成的值在1到8之间,另一个列表随机值在1到8之间。 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. 在同一试验中,第一个列表中的值不能为0,第二个列表中的值也不能为零。 I have this already in my code.
我的代码中已经有这个了。 However this is the problem I have.
但这是我的问题。
[4, 5 , 2, 5 , 1] [4,5,2,5,1]
[1, 2 , 3, 2 , 4] [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. 在listA中,两次生成5,第二个列表下方的2也生成两次。 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! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.