【问题标题】:Iteration/double iteration over a nested list in PythonPython中嵌套列表的迭代/双重迭代
【发布时间】:2020-05-23 13:41:18
【问题描述】:

如果这里已经回答了类似的问题,我很抱歉,但也许我不知道如何找到它。

我有一些看起来像这样的列表:

A1, A6 = [157, 157, 0], [407, 157, 0]
A2, A7 = [207, 157, 0], [457, 157, 0]

然后我使用另一个列表将它们分组:

A_LIST = [A1, A2, A3, A4, A5, A6, A7, A8, A9, AX]

现在我想遍历“A_LIST”,从其中的每个元素中取出第一个和第二个元素。我尝试了以下几种方式:

def between(x, val):
    if val <= x <= val + 50:
        return True


def check_pressed():
    mouse_x, mouse_y = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

if click != (0, 0, 0):
    i = 0
    for i in A_LIST:
        if between(mouse_x, A_LIST[i][0]) is True and between(mouse_y, A_LIST[i][1]) is True:

这种方法会带来一个错误,提示 unexpected type 引用“i”。我也试过这种格式: A_LIST[i[0]],但后来它说IndexError: list index out of range。假设这个问题已经解决,那么我怎么能用除A_LIST 之外的嵌套列表“喂”这个迭代?比如,取 10 个这样的集合(B_LISTC_LIST 等...),将它们放入另一个列表中,我将对其进行迭代。

提前致谢!

【问题讨论】:

    标签: python list iteration


    【解决方案1】:

    这应该可行:

    def between(x, val):
        if val <= x <= val + 50:
            return True
        else :
            return False  # don't forget this one
    
    if click != (0, 0, 0):
        # i = 0  <-- don't need this line
        for i in A_LIST:
            if between(mouse_x, i[0]) and between(mouse_y, i[1]) :
                # something you like
    

    【讨论】:

    • 非常感谢。当然,我只是没有完全理解迭代是如何工作的。我将尝试将它实施到我的第二个问题。
    猜你喜欢
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多