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

编程入门 行业动态 更新时间:2024-10-11 21:25:20
本文介绍了如何在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"循环中打印列表?

本文发布于:2023-10-28 00:04:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   列表   format   Python   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!