简体   繁体   中英

Beginner python list complehension, look up index

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)

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

Thank you

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 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

It's because mylist.index(item) is a function that looks up the index of the first time item appears in the array; that is you could call mylist.index('1') and immediately get index 2 without even putting it in a loop.

You want to do something like, where enumerate starts a zero-based index while going through the loop:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM