如何在 Python 中使用 .format() 打印“for”循环中的列表?

dev*_*hon 4 python string.format for-loop list

我是 Python 新手。我正在编写一段非常简单的代码来使用“for”循环打印列表的内容,.format()我希望输出如下,但我收到此错误:

names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
    print("{}.{}".format(i, names[i])) 
Run Code Online (Sandbox Code Playgroud)
print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str
Run Code Online (Sandbox Code Playgroud)

我想要的预期输出: 1. David 2. Peter 3. Michael 4. John 5. Bob

有人可以帮我得到那个输出吗?

Ree*_*e M 5

names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
    print("{}.{}".format(i + 1, names[i]))
Run Code Online (Sandbox Code Playgroud)

Python 列表索引引用不能是字符串。使用整数而不是索引本身(字符串)通过 for 循环迭代列表将解决此问题。在这个示例中,错误消息对于诊断问题非常有用。

  • 非常感谢@Matias Cicero ..你的这个简单答案帮助我理解了这个概念。 (2认同)