How do I display the the index of a list element in Python?
本问题已经有最佳答案,请猛点这里访问。
我有一个家庭作业。我有以下代码
1 2 3 4 | hey = ["lol","hey","water","pepsi","jam"] for item in hey: print(item) |
我是否在项目之前显示列表中的位置,如下所示:
1 2 3 4 5 | 1 lol 2 hey 3 water 4 pepsi 5 jam |
假设您在
1 2 3 4 | hey = ["lol","hey","water","pepsi","jam"] for item in hey: print(hey.index(item)+1,item) |
如果您在
1 2 3 4 | hey = ["hey","water","pepsi","jam"] for item in hey: print hey.index(item)+1,item |
使用.index(
但是,正如前面提到的,这是低效的(因为它在每次迭代中都进行查找),如果存在重复项,它将不起作用。更好的方法是使用
在
1 2 | for (i, item) in enumerate(hey, start=1): print(i, item) |
或在
1 2 | for (i, item) in enumerate(hey, start=1): print i, item |
如果需要知道您使用的是什么样的Python版本,请在命令行中键入
使用
1 2 3 4 5 6 7 8 9 10 11 | >>> hey = ["lol","hey","water","pepsi","jam"] >>> >>> for i, item in enumerate(hey, start=1): print(i,item) 1 lol 2 hey 3 water 4 pepsi 5 jam |
容易的:
1 2 3 4 | hey = ["lol","hey","water","pepsi","jam"] for (num,item) in enumerate(hey): print(num+1,item) |