如何在Python中显示列表元素的索引? [英] How do I display the the index of a list element in Python?

查看:935
本文介绍了如何在Python中显示列表元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有家庭作业.我有以下代码

I have a homework assignment. I've got the following code

hey = ["lol", "hey","water","pepsi","jam"]

for item in hey:
    print(item)

我是否在列表中显示项目之前的位置,像这样:

Do I display the position in the list before the item, like this:

1 lol
2 hey
3 water
4 pepsi
5 jam

推荐答案

假定您在Python 3中:

hey = ["lol","hey","water","pepsi","jam"]

for item in hey:
    print(hey.index(item)+1,item)

如果您在Python 2中,请仅用print语句替换print():

If you are in Python 2, replace the print() with just the print statement:

hey = ["hey","water","pepsi","jam"]

for item in hey:
    print hey.index(item)+1,item

使用<list>.index(<item>)将获得该项目的索引.

Using <list>.index(<item>) will get you the index of that item.

但是,正如已经提到的那样,这是低效的(因为它会在每次迭代中进行查找),并且如果存在重复项将无法正常工作.更好的方法是使用enumerate,因为它可以防止这两个问题.可以按照以下步骤进行.

However, as has been mentioned, this is inefficient (as it does a lookup each iteration) and will not work if there are duplicates. The better method is to use enumerate, as it prevents both of these issues. That would be done as follows.

Python 3中:

for (i, item) in enumerate(hey, start=1):
    print(i, item)

或在Python 2中:

for (i, item) in enumerate(hey, start=1):
    print i, item

如果您需要了解所使用的Python版本,请在命令行中输入python --version.

If you need to know what Python version you are using, type python --version in your command line.

这篇关于如何在Python中显示列表元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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