我是Python的新手.我正在编写一个非常简单的代码,使用带有 .format()的'for'循环来打印列表的内容,我想要的输出如下,但是我遇到了这个错误:
I'm a newbie to Python. I'm writing a very simple piece of code to print the contents of a list using 'for' loop with .format() and I want the output as below, but I'm getting this error:
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.大卫2.彼得3.迈克尔4.约翰5.鲍勃
Expected output I want: 1. David 2. Peter 3. Michael 4. John 5. Bob
有人可以帮助我获得该输出吗?
Can someone please help me to get that output?
推荐答案names = ['David', 'Peter', 'Michael', 'John', 'Bob'] for i in range (len (names)): print("{}.{}".format(i + 1, names[i]))
Python列表索引引用不能为字符串.通过for循环使用整数而不是索引本身(字符串)遍历列表将解决此问题.这是一个示例,其中错误消息对于诊断问题非常有用.
Python list index references cannot be strings. Iterating through the list via a for loop using integers rather than the indexes themselves (which are strings) will solve this issue. This is an example where the error message is very useful in diagnosing the problem.
更多推荐
如何在Python中使用.format()在"for"循环中打印列表?
发布评论