首页 > 解决方案 > check lists have identical elements using python

问题描述

Here is my code for comparing two lists and print the output as 1 in lis1 is matched at position 2 in list2 so on..Can you please let me know how i can use nested for loops and break and continue statements .Also any feasible approach to do this solution

def Iter(l1,l2):
    for i in range(len(l1)):
        for j in range(len(l2)):
            if l1[i]==l2[j]:
                print("matched at %d position"%l2[j])
            break

                    
l1=[1,2,3,4,5]
l2=[3,4,1,2,5]
Iter(l1,l2)

标签: pythonfor-loopnested

解决方案


If I understood your question correctly, you just need to find the position of each item in first list, in the second list. you can just use one loop to iterate in your first list. for each element you can check if that element exist in the second loop and if so, report the index:

def Iter(l1,l2):
for i,x in enumerate(l1):
    try:
      print(f"position {i} in first list matched at position {l2.index(x)} in second list")
    except ValueError:
      continue

the "try" and "except" part is just to handle the error that will arise when you try to use l2.index() on an element that exists in l1 but not l2.


推荐阅读