开发者

How does indexing a list with a tuple work?

I am learning Python and came across this example:

W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))
b = ['a','b','c','d','e','f','g','h','i']
for row in W:
    print b[row[0]], b[row[1]], b[row[2]]

which prints:

a b c

d e f

a e i

c e g

I am trying to figure out why!

I get that for example the first time thru the expanded version is:

print b[(0,1,2)[0]], b[(0,1,2)[1]], b[(0,1,2)[2]]

But I don't understand how the (0,1,2) is interacting. Can anyone offer an explanation? Thanks.

(this is an abbreviated version of some code for a tic tac toe game, and i开发者_JS百科t works well, I just don't get this part)


it iterates over a tuple of tuples, each row is a three-element tuple, when printing it accesses three elements of the b list by index, which is what row tuple contains.

probably, a slightly less cluttered way to do this is:

for f, s, t in W:
    print b[f], b[s], b[t]


In shot, the (0,1,2) does nothing. Its a tuple and can be indexed just like a list, so b[(0,1,2)[0]] becomes b[0] since (0,1,2)[0] == 0.

In the first step Python does b[row[0]]b[(0,1,2)[0]]b[0]'a'

Btw, to get multiple items from a sequence at once you can use a operator:

from operator import itemgetter
for row in W:
    print itemgetter(*row)(b)


Indexing a tuple just extracts the nth element, just as when indexing an array. That is, the expanded version

print b[(0,1,2)[0]], b[(0,1,2)[1]], b[(0,1,2)[2]]

is equal to

print b[0], b[1], b[2]

IE, the 0th element of the (0, 1, 2) tuple ((0, 1, 2)[0]) is 0.


Try to write down the values of all variables in each step: the result you get is right.

interaction 1:

  • row is (0,1,2)
  • b[row[0]], b[row[1]], b[row[2]] is b[(0,1,2)[0], (0,1,2)[1], (0,1,2)[2]], == b[0], b[1], b[2]

interaction 2:

  • row is (3,4,5)
  • b[row[0]], b[row[1]], b[row[2]] is b[3], b[4], b[5]


A Python interactive shell will help you see what is going on:

In [78]: W = ((0,1,2),(3,4,5),(0,4,8),(2,4,6))

In [79]: b = ['a','b','c','d','e','f','g','h','i']

In [81]: row=W[0]       # The first time throught the for-loop, row equals W[0]

In [82]: row
Out[82]: (0, 1, 2)

In [83]: row[0]
Out[83]: 0

In [84]: b[row[0]]
Out[84]: 'a'

In [85]: b[row[1]]
Out[85]: 'b'

In [86]: b[row[2]]
Out[86]: 'c'


for row in W:

first tuple placed into row is (0,1,2)

in other words, W[0] == (0,1,2)

Therefore, since `row` == (0,1,2), then row[0] == 0

So the [0]th element of b == 'a'

b[0] == 'a'

and so on...

b[1] == 'b'
b[2] == 'c'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜