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 it 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With