Search code examples
pythonlistfunctionindices

how to get all the indicesr when '"fo"','"ba"' appear together. in Python?


For a list of lists ['"fo"', '"ba"', '1','2','ect.','"fo"', '"ba"','ect.','57','"trip"'] , what's the cleanest way to get all the indices for '"fo"' when '"fo"','"ba"' appear together in the list. in Python?

Similar to one edited for 1 item answered Dec 30'14 at 21:03 and Edited Jul 28 at 21:30 by MrWonderful For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?


Solution

  • If you're looking for '"fo"' immediately followed by '"ba"', something like

    import itertools
    
    l = ['"fo"', '"ba"', '1','2','ect.','"fo"', '"ba"','ect.','57','"trip"']
    print([i for i, x in enumerate(zip(l, itertools.islice(l, 1, None))) if x == ('"fo"', '"ba"')])