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
Macos: How to Downgrade Homebrew Python
What Is the Fastest Way to Stack Numpy Arrays in a Loop
How to Run External Executable Using Python
Importing Modules from Parent Folder
How to Read Numbers from File in Python
Delete Every Non Utf-8 Symbols from String
Getting All Possible Combinations from a List With Duplicate Elements
Python Creating Dictionary from Excel Data
How to Insert String Value into Specific Column Value on Python Pandas
How to Remove the Decimal Point in a Pandas Dataframe
How to Count Occurrences of Key in List of Dictionaries
How to Get All Users in a Telegram Channel Using Telethon
How to Overwrite the Previous Print to Stdout
Finding a Substring Within a String Without Using Any Built in Functions
Skip First Couple of Lines While Reading Lines in Python File