【问题标题】:Appending tuples to a list in Python based on criteria isn't working根据条件将元组附加到 Python 中的列表不起作用
【发布时间】:2021-04-13 00:25:26
【问题描述】:

我想将星星(x,y 坐标)附加到星星列表中,要求星星距离一定距离。

stars = [(0,0)]
def position_random_star() -> tuple:
    '''  Positions a random star where it won't overlap another star  '''
    while True:
        x, y = random.randint(0,400), random.randint(0,200)
        for item in stars:
            if abs(x - item[0]) > 30 and abs(y - item[1]) > 30:
                stars.append((x,y))
                return (x,y)

但是,当我运行它时,它会生成靠得太近的星星。

for i in range(30):
    x,y = position_random_star()

print (stars)

所以我得到这样的输出: .....(246, 112), (253, 102)....

任何帮助将不胜感激!

【问题讨论】:

    标签: python list tuples


    【解决方案1】:

    在你的 for 循环中,你遍历列表中已经存在的星星。 如果列表中有至少一颗星距新的假定起点 (x,y) 足够远,则将新星附加到列表中并返回。

    据我了解,只有在距离列表中的所有星星足够远的情况下,您才想添加一颗新星 (x,y)。在这种情况下,您需要检查所有星的条件,然后如果所有星的条件都满足,则添加新星。一种方法是创建一个变量add_star,该变量将指示列表中的所有星星是否满足距离条件。如果至少有一颗恒星与新的假定恒星足够接近,我们将add_star 设置为 false。如果在完整通过列表后我们有add_path==True,我们添加一个星并返回。

    stars = [(0,0)]
    def position_random_star() -> tuple:
        '''  Positions a random star where it won't overlap another star  '''
        while True:
            x, y = random.randint(0,400), random.randint(0,200)
            add_star=True
            for item in stars:
                if abs(x - item[0]) <= 30 or abs(y - item[1]) <= 30:
                    add_star=False    
            if add_star:             
                stars.append((x,y))
                return (x,y)
    

    【讨论】:

    • 我喜欢这个解决方案...随着列表的增长,它会变得低效,因为生成适合的随机结果会更加困难。但是,我认为这里存在逻辑错误(在 OP 中也是如此)。对于要添加的星号,条件应为and 条件。合法的“星星”可以具有相同的 x 坐标,并且间隔超过 30 个单位或秒差距或太阳半径或其他任何东西。 :)。在 OP 中存在类似的逻辑错误
    • @AirSquid 我试图对 OP 的代码进行最小的更改以使其正常工作。关于效率,是的,每次都可以想出比野蛮搜索更复杂的算法。关于距离,我同意,我认为将欧几里得距离用于天文应用更合适。
    • 非常感谢!这是一个完美的答案,有道理!!!
    猜你喜欢
    • 2018-02-08
    • 2016-11-19
    • 2022-01-27
    • 2018-09-25
    • 2022-10-14
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多