Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

print an element of a list(let's say 3 lines and 2 rows,two-dimensional list) .what i'm doing wrong? for python

playerscoins=[[10 for i in range(2)]for j in range(3)]

def currentbalance(coins):
    print("Current balance:")
    for i in range(3):
        print("Player %i has %i coins." % i , coins[i,0])

currentbalance(playerscoins)
Current balance:
Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
    currentbalance(playerscoins)
  File "<pyshell#82>", line 4, in currentbalance
    print("Player %i has %i coins." % i , coins[i,0])
TypeError: not enough arguments for format string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two things wrong with your code:

  1. 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].
  2. 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.")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...