【问题标题】:How can i get the list indices from nested lists whilst checking the contents of the list cell?如何在检查列表单元格内容的同时从嵌套列表中获取列表索引?
【发布时间】:2023-03-17 04:10:01
【问题描述】:

基本上我正在制作一个使用网格的基于 ascii 回合的游戏。我希望能够创建第二个网格或“层”,它保存有关该单元格的数据,并通过共享相同的索引值与第一个网格有直接关系。虽然我在以前的游戏版本中取得了一些工作成果,但我还是被卡住了,因为我不知道如何获取列表索引。

现在我发现我可以使用 inumerate() 函数获取索引。下面是一个练习 我试过的程序:

    #some example lists
    list = [[0, 2],[2, 3], [9,4], [5, 9]]
    list2 =[[0, 0],[0, 0],[0, 0],[0, 0]]

    # a for loop to iterate through all elements of the nested list
    # using enumerate to to gain access to the list indices

    for i, j in enumerate(list):
        for ii, jj in enumerate(list):

            # if statements below seemingly not working.
            # jj is supposed to hold the contents of the current list cell
            # also when the 'else' kicks in because jj didn't match anything 
            # throws an error index out of range

            if jj == 0:
                list2[i][ii] = 'A'
            elif jj == 2:
                list2[i][ii] = 'C'
            else:
                list2[i][ii] = 1
        print(i, ii)
        print(jj)
    for i in list2:
        print(i)

程序不工作,(我评论了我在上面的代码中遇到的错误),我想知道如何让它工作。非常感谢您的时间和耐心。

【问题讨论】:

  • for i, j in enumerate(list) 我想你的意思是for i, j in enumerate(list2)for ii, jj in enumerate(list) 我想你的意思是for ii, jj in enumerate(j)
  • 我想你的意思是for ii, jj in enumerate(j)
  • @aecolley 我认为你和@inspectorG4dget 当你说我应该有for ii, jj in enumerate(j) 而不是(列表)时,但list2 是我希望根据第一个使用ii 的列表中的内容来改变的列表跟踪索引,所以我不知道为什么要枚举它。但是,是的,将第二个枚举更改为 (j) 使代码按预期工作,非常感谢你们!
  • 也许你想在外循环中枚举(list),在内循环中枚举(list2[i])?
  • 另外,将变量命名为 listfiledict 是一个可怕的想法。避免命名变量与python数据结构共享名称

标签: python matrix iteration layer enumerate


【解决方案1】:
  1. 请勿使用内置函数的名称作为变量的名称。
  2. 使用有意义的变量名而不是无意义的变量名,例如 ii、jj,这会使您的代码难以阅读

我认为您想根据第一个列表的值为第二个列表分配新值。试试这个:

#!/usr/bin/env python
#-*- coding:utf-8 -*-


#some example myLists
myList = [[0, 2],[2, 3], [9,4], [5, 9]]
myList2 =[[0, 0],[0, 0],[0, 0],[0, 0]]

for index0, value0 in enumerate(myList):

    for index1, value1 in enumerate(value0):

        if value1 == 0:
            myList2[index0][index1] = 'A'
        elif value1 == 2:
            myList2[index0][index1] = 'C'
        else:
            myList2[index0][index1] = 'else'

print myList2      

希望对你有帮助。

【讨论】:

    【解决方案2】:

    由于将访问两个列表中的每个单元格,并且每个单元格的索引直接映射(列表中的 0 映射到列表 2 中的 0),当前索引是隐含的,可以使用列表推导。

    grid = [[0, 2], [2, 3], [9, 4], [5, 9]]
    mapping = {0: 'A', 2: 'C'}
    grid2 = [[mapping.get(cell, 1) for cell in row] for row in grid]
    

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2020-07-28
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多