There are two things wrong with your code:
- You're trying to use a tuple as an index to
coins
. Since coins
is a list of lists, you want to do coins[i]
to get the i-th list and then [0]
to get the first element of that list, making the expression coins[i][0]
.
- You're not passing a tuple to the format string. Since there are no parens around
i, coins[i][0]
, the second part is getting interpreted as another arg to print
rather than as another part of the operand to %
.
Fixing those errors would look like:
for i in range(3):
print("Player %i has %i coins." % (i, coins[i][0]))
A less confusing way to do this (if you're on Python 3, which everyone should be IMO) is to use f-strings rather than the %
operator:
for i in range(3):
print(f"Player {i} has {coins[i][0]} coins.")
You could also simplify the whole problem of how to index the lists by using enumerate
to iterate over each row of coins
. This also saves you from having to hard-code in the number of rows:
for p, row in enumerate(coins):
print(f"Player {p} has {row[0]} coins.")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…