【问题标题】:how do I simplify searching for a list item by an index?如何简化按索引搜索列表项?
【发布时间】:2019-12-11 17:18:20
【问题描述】:

我有一个简单的程序:

pos = [1,2]
searched = [
    [1,3,4,6],
    [2,6,7,8],
    [0,1,2,8],
    [5,6,9,2]
]
print(searched[pos[0]][pos[1]])
7

现在我想要的是摆脱searched[pos[0]][pos[1]] 并输入类似searched[[pos]] 的方法。

有没有办法,还是每次都要写出来

我得到了很多建议,但我正在寻找一种方法可以在一条简洁的线路中做到这一点,简化一切。
这意味着诸如使用函数、转换为特定字典甚至枚举之类的事情对我不起作用,所以对于以后看这篇文章的人来说:
.
我建议在定义所述变量时使用np.array(variable),以便您可以使用variable[pos]

【问题讨论】:

  • 不,Python list 对象不支持。不过,你总是可以编写一个函数
  • 有很多选择。您可以编写帮助函数,例如 def get_val(matrix, pos): 返回此位置,然后调用它 get_val(searched, pos)
  • 或使用numpy,因为这将支持您所需的索引语法

标签: python python-3.x list simplify


【解决方案1】:

不知道你是否可以接受,但是一个函数可以做到:

def search_for_list_item_by_index(a_list, row, col):
    return a_list[row][col]

print(search_for_list_item_by_index(searched, 1, 2))

这会按预期打印7

【讨论】:

    【解决方案2】:

    您可以按照@oppressionslayer 的建议将您的数组转换为numpy。 另一种方法是创建一个字典并按如下方式使用它:

    pos = [1,2]
    searched = [
        [1,3,4,6],
        [2,6,7,8],
        [0,1,2,8],
        [5,6,9,2]
    ]
    m=4 # width of the searched array
    n=4 # hight of the searched array
    
    searched = {(i,j):searched[i][j] for j in range(m) for i in range(n)}
    
    print(searched[1,2]) # prints 7
    print(searched[tuple(pos)]) # prints 7
    

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      您可以将其转换为一个 numpy 数组并进行搜索:

      import numpy as np
      pos = [1,2] 
      searched = np.array([ 
        [1,3,4,6], 
        [2,6,7,8], 
        [0,1,2,8], 
        [5,6,9,2] 
        ]) 
      print(searched[1,2])  
      # 7
      

      【讨论】:

        【解决方案4】:

        您可以使用以下功能:

        def func(idx, lst):
            for i in idx:
                lst = lst[i]
            return lst
        
        func(pos, searched)
        # 7
        

        【讨论】:

          【解决方案5】:

          我会使用字典方法like HNMN3,但有趣的是您可以使用enumerate 泛化到非矩形列表:

          searched = {(row,col):item
                        for row,elems in enumerate(searched)
                          for col,item in enumerate(elems)}
          

          或使用flatten_data from my answer here,它做同样的事情,但适用于完全任意的嵌套,包括字典。可能不是你想要的方向,但值得一提。

          data = flatten_data(searched)
          pos = [1,2]
          print(data[1,2])
          print(data[tuple(pos)])
          

          【讨论】:

            猜你喜欢
            • 2015-02-07
            • 1970-01-01
            • 2018-05-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多