python - python中的高效列表比较
问题描述
我想有效地比较两个列表并确定两者是否共享完全相同的元素。
列表可以是None
、空的和各种长度的。列表中元素的顺序无关紧要,所以['a', 'b', 'c'] == ['a', 'c', 'b']
在我的情况下是相等的。
我目前的解决方案如下所示:
def list_a_equals_list_b(list_a, list_b):
if list_a != None and list_b != None:
if len(list_a) != len(list_b):
return False
else:
return len(frozenset(list_a).intersection(list_b)) == len(list_a)
elif list_a == None and list_b == None:
return True
else:
return False
有没有更有效的方法来比较这些列表?
谢谢!
解决方案
如果您在任一列表中都没有重复项,则可以使用一组:
if listA == listB \
or listA and listB \
and len(listA) == len(listB) \
and not set(listA).symmetric_difference(listB):
# lists have the same elements
else:
# there are differences
如果您确实允许重复,那么您可以使用集合中的计数器(如果您没有重复也可以使用)
from collections import Counter
if listA == listB \
or listA and listB \
and len(listA) == len(listB) \
and Counter(listA)==Counter(listB):
# lists have the same elements
else:
# there are differences
推荐阅读
- python - 将scrapy输出拆分到不同的列
- javascript - 获取所有数组 [1, 1, 1, 1, 1, 0, 0, 0, 0] 的排列
- python - Python(源代码构建),无法让张量流工作
- ios - 当父级有点击事件时,Nativescript 选项卡不起作用
- php - 如何使用 laravel eluoquent 在测验应用程序中获得单一类别的问题
- xamarin.forms - SearchBar 中的取消按钮导致应用程序崩溃(Xamarin 表单)
- android - 在 Android 上的 PreferenceFragmentCompat 中永远不会调用 onPreferenceStartScreen()
- r - R:文件名列表结果无法识别实际读取文件(文件名字符编码问题)
- html - 更改相对 div 中绝对按钮的顺序
- pandas - Pandas Dataframe:将列拆分为多列