[英]python: accessing element in list of lists by single object
在 Python 中,可以通過以下方式訪問 2dim numpy 數組中的元素:
matrix = numpy.array([[1,2],[3,4]])
indices = 1, 1
matrix[indices]
在這種情況下,我們可以將矩陣中元素的位置存儲在單個變量(此處為索引)中。 列表列表有類似的東西嗎? 換句話說:如果我們不能使用 numpy,有沒有比 numpy 更好的方法
matrix = [[1,2],[3,4]]
indices = 1, 1
matrix[indices[0]][indices[1]] # this line is ugly, isnt it?
替代第二個示例,您可以使用:
matrix = [[1,2],[3,4]]
fst_pos, snd_pos = 1, 1
matrix[fst_pos][snd_pos]
>>4
這樣您就可以避免使用索引變量的索引(刪除不必要的括號使用)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.