python - 这个循环方法正确吗? Python 3.4.3

标签 python loops python-3.x location

所以,我想要一组彼此不同的 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/

相关文章:

python - 树莓派人数计入谷歌表格

python - 如何在 Python 3 中键入提示生成器?

java - 我的 Java 网络项目中存在循环和流控制问题

python - 调用函数并打印函数名称

python - Matplotlib 2 字体不一致

python-3.x - 使用 tox 在后台运行命令

python - [ :-1] mean/do in python? 是什么意思

python - 类型错误 : Object of type 'mappingproxy' is not JSON serializable

php - 使用PHP循环多次查询MYSQL数据库

python - Bokeh - 如何在两个不同的选项卡中拥有相同的小部件(或复制小部件)?