In Python, how can I find the index of the first item in a list that is NOT some value?

前端 未结 5 387
小鲜肉
小鲜肉 2020-12-14 20:14

Python\'s list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x.

Basica

5条回答
  •  借酒劲吻你
    2020-12-14 20:30

    A silly itertools-based solution:)

    import itertools as it, operator as op, functools as ft
    
    def index_ne(item, sequence):
        sequence= iter(sequence)
        counter= it.count(-1) # start counting at -1
        pairs= it.izip(sequence, counter) # pair them
        get_1st= it.imap(op.itemgetter(0), pairs) # drop the used counter value
        ne_scanner= it.ifilter(ft.partial(op.ne, item), get_1st) # get only not-equals
        try:
            ne_scanner.next() # this should be the first not equal
        except StopIteration:
            return None # or raise some exception, all items equal to item
        else:
            return counter.next() # should be the index of the not-equal item
    
    if __name__ == "__main__":
        import random
    
        test_data= [0]*20
        print "failure", index_ne(0, test_data)
    
        index= random.randrange(len(test_data))
        test_data[index]= 1
        print "success:", index_ne(0, test_data), "should be", index
    

    All this just to take advantage of the itertools.count counting :)

提交回复
热议问题