python-如何查找两个列表中存在但具有不同索引的元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何查找两个列表中存在但具有不同索引的元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1020字,纯文字阅读大概需要2分钟。
内容图文
![python-如何查找两个列表中存在但具有不同索引的元素](/upload/InfoBanner/zyjiaocheng/658/ed70bec74e964705a16783d5c6201078.jpg)
我有两个长度相同的列表,其中包含各种不同的元素.我正在尝试比较它们,以找到两个列表中都存在但具有不同索引的元素数量.
这是一些示例输入/输出来说明我的意思:
>>> compare([1, 2, 3, 4], [4, 3, 2, 1])
4
>>> compare([1, 2, 3], [1, 2, 3])
0
# Each item in the first list has the same index in the other
>>> compare([1, 2, 4, 4], [1, 4, 4, 2])
2
# The 3rd '4' in both lists don't count, since they have the same indexes
>>> compare([1, 2, 3, 3], [5, 3, 5, 5])
1
# Duplicates don't count
列表大小始终相同.
这是我到目前为止的算法:
def compare(list1, list2):
# Eliminate any direct matches
list1 = [a for (a, b) in zip(list1, list2) if a != b]
list2 = [b for (a, b) in zip(list1, list2) if a != b]
out = 0
for possible in list1:
if possible in list2:
index = list2.index(possible)
del list2[index]
out += 1
return out
有没有更简洁,更有说服力的方式来做同样的事情?
解决方法:
此python函数确实适用于您提供的示例:
def compare(list1, list2):
D = {e:i for i, e in enumerate(list1)}
return len(set(e for i, e in enumerate(list2) if D.get(e) not in (None, i)))
内容总结
以上是互联网集市为您收集整理的python-如何查找两个列表中存在但具有不同索引的元素全部内容,希望文章能够帮你解决python-如何查找两个列表中存在但具有不同索引的元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。