如何有效地比较Python中的两个无序列表(不是集合)? [英] How to efficiently compare two unordered lists (not sets) in Python?

查看:1614
本文介绍了如何有效地比较Python中的两个无序列表(不是集合)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  a = [1,2,3,1,2,3] 
b = [3,2,1,3,2,1]

a& b应该被认为是平等的,因为它们具有完全相同的元素,只是以不同的顺序。



事实是,我的实际列表将包括对象

https://docs.python.org/3.5/library/collections.html#collections.Counterrel =nofollow> Counter() 方法是最好的(如果你的对象是hashable):

  def compare(s,t):
return Counter(s)== Counter(t)

O(n log n) sorted() 方法是次好的(如果您的对象是可订购的): p>

  def compare(s,t):
return sorted(s)== sorted(t)

O(n * n):如果对象既不可哈希也不可排序,使用平等:

  def compare(s,t):
t = list(t)#make a mutable copy
try:
在元素中的元素:
t.remove(elem)
(ValueError除外):
return False
return not t


a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]

a & b should be considered equal, because they have exactly the same elements, only in different order.

The thing is, my actual lists will consist of objects (my class instances), not integers.

解决方案

O(n): The Counter() method is best (if your objects are hashable):

def compare(s, t):
    return Counter(s) == Counter(t)

O(n log n): The sorted() method is next best (if your objects are orderable):

def compare(s, t):
    return sorted(s) == sorted(t)

O(n * n): If the objects are neither hashable, nor orderable, you can use equality:

def compare(s, t):
    t = list(t)   # make a mutable copy
    try:
        for elem in s:
            t.remove(elem)
    except ValueError:
        return False
    return not t

这篇关于如何有效地比较Python中的两个无序列表(不是集合)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆