[英]python: accessing element in list of lists by single object
In Python, one can access an element in a 2dim numpy-array via:在 Python 中,可以通过以下方式访问 2dim numpy 数组中的元素:
matrix = numpy.array([[1,2],[3,4]])
indices = 1, 1
matrix[indices]
in this case, we can store the position of an element in the matrix within a single variable (here indices).在这种情况下,我们可以将矩阵中元素的位置存储在单个变量(此处为索引)中。 Is there a similar thing available for a list of lists?
列表列表有类似的东西吗? In other word: If we cant use numpy, is there a better way than
换句话说:如果我们不能使用 numpy,有没有比 numpy 更好的方法
matrix = [[1,2],[3,4]]
indices = 1, 1
matrix[indices[0]][indices[1]] # this line is ugly, isnt it?
Alternatively to your second example, you could use:替代第二个示例,您可以使用:
matrix = [[1,2],[3,4]]
fst_pos, snd_pos = 1, 1
matrix[fst_pos][snd_pos]
>>4
This way you're avoiding using the indexing of your index variable(removes unnecessary use of brackets)这样您就可以避免使用索引变量的索引(删除不必要的括号使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.