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

devPython

我是Python的新手。我正在编写一个非常简单的代码来使用'for'循环来打印列表的内容,.format()并且我希望输出如下,但是我遇到了这个错误:

names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in names:
    print("{}.{}".format(i, names[i])) 

print("{}.{}".format(i,breakfastMenu[i]))
TypeError: list indices must be integers or slices, not str

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

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

里斯·默瑟
names = ['David', 'Peter', 'Michael', 'John', 'Bob']
for i in range (len (names)):
    print("{}.{}".format(i + 1, names[i]))

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章