问题
I just started with python and very soon wondered if indexing a nested list with a tuple was possible. Something like: elements[(1,1)]
One example where I wanted to do that was something similar to the code below in which I save some positions of the matrix that I will later need to access in a tuple called index.
index = ( (0,0), (0,2), (2,0), (2,2) )
elements = [ [ 'a', 'b', 'c'],
[ 'c', 'd', 'e'],
[ 'f', 'g', 'h'] ]
for i in index:
print (elements [ i[0] ] [ i[1] ])
# I would like to do this:
# print(elements[i])
It seems like a useful feature. Is there any way of doing it? Or perhaps a simple alternative?
回答1:
Yes, you can do that. I wrote a similar example:
index = [ [0,0], [0,2], [2,0], [2,2] ]
elements = [ [ 'a', 'b', 'c'],
[ 'c', 'd', 'e'],
[ 'f', 'g', 'h'] ]
for i,j in index:
print (elements [ i ] [ j ])
a c f h
回答2:
If you really want to use tuples for indexing you can implement your own class that extends list
and redefines __getattr__
to work with tuples and use that:
class TList(list):
def __getitem__(self, index):
if hasattr(index, "__iter__"):
# index is list-like, traverse downwards
item = self
for i in index:
item = item[i]
return item
# index is not list-like, let list.__getitem__ handle it
return super().__getitem__(index)
elements = TList([ [ 'a', 'b', 'c'],
[ 'c', 'd', 'e'],
[ 'f', 'g', 'h'] ])
index = ( (0,0), (0,2), (2,0), (2,2) )
for i in index:
print(elements[i])
a
c
f
h
回答3:
# I would like to do this: # print(elements[i])
No you cannot index a specific value of a nested list in this way.
The only slightly better way would be to "unpack" the tuples are you're iterating over them:
Example:
for i, j in index:
print(elements[i][j])
See: Tuples ans Sequences
回答4:
If you want to print everything in elements
index = ( (0,0), (0,2), (2,0), (2,2) )
elements = [ [ 'a', 'b', 'c'],
[ 'c', 'd', 'e'],
[ 'f', 'g', 'h'] ]
for row in elements:
for i in range(len(row)):
print (row[i])
回答5:
You can use list comprehensions:
index = ((0, 0), (0, 2), (2, 0), (2, 2))
elements = [['a', 'b', 'c'],
['c', 'd', 'e'],
['f', 'g', 'h']]
tmp = [print(elements[i][j]) for i,j in index]
来源:https://stackoverflow.com/questions/30341008/is-it-possible-to-index-nested-lists-using-tuples-in-python