Finding the index of an item in a list

后端 未结 30 3878
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  耶瑟儿~
    2020-11-21 05:37

    Getting all the occurrences and the position of one or more (identical) items in a list

    With enumerate(alist) you can store the first element (n) that is the index of the list when the element x is equal to what you look for.

    >>> alist = ['foo', 'spam', 'egg', 'foo']
    >>> foo_indexes = [n for n,x in enumerate(alist) if x=='foo']
    >>> foo_indexes
    [0, 3]
    >>>
    

    Let's make our function findindex

    This function takes the item and the list as arguments and return the position of the item in the list, like we saw before.

    def indexlist(item2find, list_or_string):
      "Returns all indexes of an item in a list or a string"
      return [n for n,item in enumerate(list_or_string) if item==item2find]
    
    print(indexlist("1", "010101010"))
    

    Output


    [1, 3, 5, 7]
    

    Simple

    for n, i in enumerate([1, 2, 3, 4, 1]):
        if i == 1:
            print(n)
    

    Output:

    0
    4
    

提交回复
热议问题