Search code examples
pythonlistindexingcomparisonlist-comprehension

Compare 2 lists, based on index from 2 other lists, and save index in new list with list comprehension


So what I am trying to do is:

1) Find where list1[y] == list2[x]

2) Determine if list3[y] < (0.4 list4[x])

3) If so, store the index y in a new list of indexes

This loop works, however it takes almost a full minute to run with my data set. I want to know if I can do this with list comprehension.

Thanks in advance for anybody's help.

    for y in range(len(list1)):
        for x in range(len(list2)):
            if list1[y] == list2[x]:
                if list3[y] < (0.4 * list4[x]):
                    list5.append(y)

Solution

  • I'm not sure if this will provide a significant performance increase, but try this:

    list5 = [y for y, val1 in enumerate(list1) for x, val2 in enumerate(list2) if val1 == val2 and list3[y] < (0.4 * list4[x])]