[英]How can I get index from an element in a mulitidimensional list?
Here is what I'm trying to do:这是我正在尝试做的事情:
board = [[0, 1, 2, 3] , [4, 5, 6, 7] , [8, 9, 10, 11] , [12, 13, 14, 15,]].index("8")
print(board)
I get the error:我得到错误:
ValueError '8' is not in the list
How can I get the index from this element?如何从该元素中获取索引?
You can iterate and return the index value:您可以迭代并返回索引值:
next((i for i, x in enumerate(board) if n in x), 'not found')
board = [[ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 , 15 , ]]
n = 8
print(next((i for i, x in enumerate(board) if n in x), 'not found'))
This prints:这打印:
2
In case you want all indices of the value, switch to a list comprehension:如果您想要该值的所有索引,请切换到列表理解:
[i for i, x in enumerate(board) if n in x]
I don't think there is a built in way to do it.我认为没有内置的方法可以做到这一点。 I would do it using numpy:我会使用 numpy 来做到这一点:
import numpy as np
board = [[ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [
12 , 13 , 14 , 15 , ]]
b=np.asarray(board)
print(np.argwhere(b==8))
result: array([[2, 0]])
结果: array([[2, 0]])
this assumes there is only one occurrence of an element.这假设一个元素只出现一次。
board = [[ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 , 15 ]]
var = [ele for ele in board if 8 in ele][0]
# check if element is not present in the list
if len(var) == 0:
print('-1')
else:
print('index: (', board.index(var), var.index(8), ')')
output: output:
index: ( 2 0 )
What index
in python does is find the element match which in your case are all lists and you are trying to match a int
python 中的index
是找到在您的情况下都是列表的元素匹配,并且您正在尝试匹配一个int
You can use numpy
to get the location您可以使用numpy
来获取位置
import numpy as np
board = [[ 0 , 1 , 2 , 3 ] , [ 4 , 5 , 6 , 7 ] , [ 8 , 9 , 10 , 11 ] , [ 12 , 13 , 14 , 15 ]]
np.where(np.array(board) == 8)
(array([2]), array([0]))
which is basically board[2][0]
这基本上是board[2][0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.