我有一个元组列表:
tuples_list = [(1,0), (2,3), (3,2), (2,0)]
我想使用其中一些元组访问二维数组a
的元素,例如
for i in range(3):
print a[tuples_list[i]]
应该输出a[1][0], a[2][3], a[3][2]
的值。
只是为了澄清,a
就像是
a = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]
答案 0 :(得分:1)
实现这一目标的典型方法是在for循环中使用元组解包,如下所示:
a = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20],[21,22,23,24]]
tuples_list = [(1,0), (2,3), (3,2), (2,0)]
for x,y in tuples_list:
print a[x][y]
答案 1 :(得分:0)
使用元组解包将元组拆分为两个变量:
>>> tuples_list = [(1,0), (2,3), (3,2), (2,0)]
>>> a = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], [17,18,19,20], [21,22,23,24]]
>>> for indexes in tuples_list:
... i, j = indexes # tuple unpacking
... print a[i][j]
...
5
12
15
9
>>> for i, j in tuples_list: # tuple unpacking
... print a[i][j]
...
5
12
15
9
答案 2 :(得分:0)
这应该做的工作:
for i in range(len(tuples_list)):
list_index, element_index = tuples_list[i]
print(a[list_index][element_index])