所以,我想要一组彼此不同的 XY 位置。为了做到这一点,我使用了一个列表来存储随机生成的变量 XY。如果该位置不在列表中,则会将其添加到列表中,如果在列表中,则会为其重新创建一个位置。
我不确定这是否适用于所有情况,并且想知道是否有更好的方法。
import random
positionList = []
for i in range(6):
position = [random.randint(0,5),random.randint(0,5)]
print("Original", position)
while position in positionList:
position = [random.randint(0,5),random.randint(0,5)]
positionList.append(position)
print(position)
重新制作的位置是否与列表中的其他位置相同?
最佳答案
重新制作的位置是否与列表中的其他位置相同?
是的,因为你使用的是随机的。如果您想确保保留唯一的项目,您可以使用 set
对象来实现该目的,该对象为您保留唯一的项目。但请注意,由于列表不是可哈希对象,因此您应该为对(如元组)使用可哈希容器:
>>> position_set = set()
>>>
>>> while len(position_set) != 6:
... position = (random.randint(0,5), random.randint(0,5))
... position_set.add(position)
...
>>> position_set
set([(3, 2), (5, 0), (2, 5), (5, 2), (1, 0), (3, 5)])
关于python - 这个循环方法正确吗? Python 3.4.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521012/