python - 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)
解决方案
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.
推荐阅读
- c# - 如何wpf画布背景连续更改图像
- java - 跳轨方式
- ruby-on-rails - 如何为 rspec 中的创建和更新操作编写测试用例?
- r - 在光栅图像中将双月儒略日转换为日期
- c# - ASP.NET:使用#temp 表存储会话以在其上运行其他存储过程
- apache-spark - pyspark 哈希是否保证不同输入的唯一结果?
- javascript - Discord 机器人删除命令
- wordpress - 在类别列表下提取单个帖子特色图像
- python - Python 避免使用 for 循环或需要缩短代码库
- sql - 当 Event Action = "something" 时更新 GA 的事件类别