初学者python列表补充,查找索引 [英] Beginner python list complehension, look up index

查看:143
本文介绍了初学者python列表补充,查找索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我想要所有1的索引位置:

I have the following code, and I would like the index position of all the 1's:

mylist = ['0', '0', '1', '1', '0']

for item in mylist:
    if item is '1':
        print mylist.index(item)

有人可以解释为什么这个程序的输出是2,2而不是2,3 ?

Can someone explain why the output of this program is 2, 2 instead of 2, 3 ?

谢谢

推荐答案

python builtin enumerate 返回索引和元素的元组。您只需迭代枚举元组并仅过滤那些符合搜索条件的元素

python builtin enumerate returns a tuple of the index and the element. You just need to iterate over the enumerated tuple and filter only those elements which matches the search criteria

>>> mylist = ['0', '0', '1', '1', '0']
>>> [i for i,e in enumerate(mylist) if e == '1']
[2, 3]

现在回到你的代码。您需要了解三个问题

Now coming back to your code. There are three issues that you need to understand


  1. Python列表方法索引返回干草中第一次出现针的位置。因此,在mylist中搜索1将始终返回2.您需要缓存先前的索引并将其用于后续搜索

  2. 您的缩进不正确且您的打印应该在<$ c内$ c>如果阻止

  3. 您使用 是不正确的。 不检查是否相等,只是验证两个元素是否具有相同的引用。虽然在这种情况下它会起作用但最好避免。

  1. Python list method index returns the position of the first occurrence of the needle in the hay. So searching '1' in mylist would always return 2. You need to cache the previous index and use it for subsequent search
  2. Your indentation is incorrect and your print should be inside the if block
  3. Your use of is is incorrect. is doesn't check for equality but just verifies if both the elements have the same reference. Though in this case it will work but its better to avoid.

>>> index = 0
>>> for item in mylist:
    if item == '1':
        index =  mylist.index(item, index + 1)
        print index


2
3


最后为什么担心在枚举时使用索引。

Finally why worry about using index when you have enumerate.

>>> for index, item in enumerate(mylist):
    if item == '1':
        print index


2
3

这篇关于初学者python列表补充,查找索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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