Comparing Items in Lists Within Same Indices Python

Identify index of all elements in a list comparing with another list

You can iterate through the enumeration of A to keep track of the indices and yield the values where they match:

A = [100,200,300,200,400,500,600,400,700,200,500,800]
B = [100,200,200,500,600,200,500]

def get_indices(A, B):
a_it = enumerate(A)
for n in B:
for i, an in a_it:
if n == an:
yield i
break

list(get_indices(A, B))
# [0, 1, 3, 5, 6, 9, 10]

This avoids using index() multiple times.

Compare items on the same index on 2 lists

As you want :

taking the item that comes before the match

One line solution :

print([(list1[index-1],item) for index,item in enumerate(list1) for item1 in list2 if item==item1[1]])

output:

[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]

Detailed solution:

list_3=[]
for index,item in enumerate(list1):
for item1 in list2:
if item==item1[1]:
list_3.append((list1[index-1],item))

print(list_3)

output:

[('ARHEL 7 FY2017 64-bit', '7.2'), ('BRHEL 7 FY2017 64-bit', '7.3')]


Related Topics



Leave a reply



Submit