如何在Python中使用.format()在"for"循环中打印列表? [英] How to print the list in 'for' loop using .format() in Python?

查看:115
本文介绍了如何在Python中使用.format()在"for"循环中打印列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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"循环中打印列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆