【问题标题】:How to compare a single list, with a range of lists?如何将单个列表与一系列列表进行比较?
【发布时间】:2018-06-02 13:12:16
【问题描述】:

从随机导入randint

def apple(player):

    """Returns a new unoccupied position (tuple). Used to spawn a new `apple` at
    that position.  Microbit LED 5x5"""

    Args:
        player (list of tuples): List of player coordinates

    Returns:
        A new unoccupied position (tuple)

    """
    apple = list((0,0))

    # loop to get each tuple, as list
    for i in range(0, len(player)):
        p = list(player[i])

    dot[0] = randint(0,4)
    dot[1] = randint(0,4)
    x= list (apple)

    if x!= p:
        return tuple((dot))

如果我用

运行函数
player = [(0,0), (1,0), (2,0), (3,0), (4,0),
          (0,1), (1,1), (2,1), (3,1), (4,1),
          (0,2), (1,2), (2,2), (3,2), (4,2),
          (0,3), (1,3), (2,3), (3,3), (4,3),
          (0,4), (1,4), (2,4), (3,4),]

它应该给我 (4,4),但它确实有效。 整个函数忽略了我的不平等陈述:(

【问题讨论】:

  • len(player)=24 我想你可能会注意到这里并纠正自己
  • 如果你想做的是在地图上找到一个空闲位置,为什么还要使用 randint?

标签: python-3.x list if-statement random tuples


【解决方案1】:

如果我对您的理解正确,玩家是“您的游戏地图,其中包含项目当前的坐标”,您想找到一个可以种植苹果的空地。如果有几个可能的地方你想随机选择一个

如果这是真的,那么这个脚本会这样做:

from operator import itemgetter
import random

def apple(player):
    max_x = max(player, key=itemgetter(0))[0]
    max_y = max(player, key=itemgetter(1))[1]
    candidates = []
    for x in range(max_x + 1):
        for y in range(max_y + 1):
            if (x, y) not in player:
                candidates.append((x,y))
    return random.choice(candidates)

脚本假定最小坐标是(0,0) 并搜索最大坐标本身(如果您事先知道这一点,您可以将两个参数max_xmax_y 添加到apple()。然后它只是迭代所有可能的坐标查找是否有空点,收集candidates中所有可能的坐标,然后随机选择一个坐标返回。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多