如何简化按索引搜索列表项?

2024-04-20 14:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的程序:

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]]之类的内容。你知道吗

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

I have gotten a lot of suggestions, but what I am searching for is a way to do this in one neat line, simplifying everything.
That means that things like using a function, converting to a specific dictionary or even enumerate don't work for me, so for anyone looking at this post later:
.
I suggest using np.array(variable) while defining said variable so you can use variable[pos]


Tags: to方法pos程序内容for键入so
3条回答

您可以按照@suppressionslayer的建议将数组转换为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

希望这有帮助!!你知道吗

您可以将其转换为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

不知道您是否接受,但函数可以:

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。你知道吗

相关问题 更多 >