gpt4 book ai didi

python - 如何简化通过索引搜索列表项的过程?

转载 作者:行者123 更新时间:2023-12-02 11:46:27 25 4
gpt4 key购买 nike

我有一个简单的程序:

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]

最佳答案

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

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

关于python - 如何简化通过索引搜索列表项的过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59290949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com