如何在python中格式化列表输出

时间:2015-04-18 20:47:36

标签: python for-loop

我正在尝试格式化索引的输出和列表:

[6]
[7]
[8]
[9]
The answers should be: 
['b', 'c', 'a', 'c']`

更像这样:

[6]  b   
[7]  c
[8]  a    
[9]  c

以下是代码段:

print( "Here are the questions the you got wrong: ")
for i in range (0, 10):
    if q[i] != answers[i]:
        print ( [i+1],)
    else:
        ("You got all of the questions correct, Good Job. ")
print("The answers should be: ")
print(wrongList)

3 个答案:

答案 0 :(得分:2)

你没有收集wrongList,但它很容易做到:

print("The answers should be: ")
for i in range (0, 10):
    if q[i] != answers[i]:
        print (q[i], answers[i])

答案 1 :(得分:1)

只需打印answers[i]

for i in range (10):
    print("[{}] {}".format(i+1, answers[i])

如果只有十个答案,您可以使用enumerate,其起始值为1,enumerate(answers, start=1),或者如果超过十个,则必须对其进行分割:

 for i  answer in enumerate(answers[:10], start=1)

您还可以zip并忘记编制索引:

for i, (a, b) in enumerate(zip(answers, p),1):
    if a != b:
       print("[{}] {}".format(count, a))
    else:
       print("You got all of the questions correct, Good Job. ")

"[{}] {}".format(count, a)正在使用str.format,这通常是首选方法。

答案 2 :(得分:1)

您可以使用enumerate遍历列表并获取索引:

for i, answer in enumerate(answers):
    print("[%s] %s" % (i, answer))

如果print声明没有意义,请查看string formatting的文档。