# 确定2个列表是否具有相同的元素，而不pipe顺序如何？

``x = ['a', 'b'] y = ['b', 'a']` `

### 4 Solutions collect form web for “确定2个列表是否具有相同的元素，而不pipe顺序如何？”

` `import collections collections.Counter(x) == collections.Counter(y)` `

` `set(x) == set(y)` `

` `sorted(x) == sorted(y)` `

` `def equal_ignore_order(a, b): """ Use only when elements are neither hashable nor sortable! """ unmatched = list(b) for element in a: try: unmatched.remove(element) except ValueError: return False return not unmatched` `

` `x = ['a', 'b'] y = ['b', 'a']` `

` `set(x) == set(y) # prefer this if elements are hashable` `

` `from collections import Counter Counter(x) == Counter(y)` `

` `sorted(x) == sorted(y)` `

# 实证实验

` `import timeit import random from collections import Counter data = [str(random.randint(0, 100000)) for i in xrange(100)] data2 = data[:] # copy the list into a new one def sets_equal(): return set(data) == set(data2) def counters_equal(): return Counter(data) == Counter(data2) def sorted_lists_equal(): return sorted(data) == sorted(data2)` `

` `>>> min(timeit.repeat(sets_equal)) 13.976069927215576 >>> min(timeit.repeat(counters_equal)) 73.17287588119507 >>> min(timeit.repeat(sorted_lists_equal)) 36.177085876464844` `

` `>>> A = [0, 1] >>> B = [1, 0] >>> C = [0, 2] >>> not sum([not i in A for i in B]) True >>> not sum([not i in A for i in C]) False >>>` `

` `>>> A = [0, 1, 2] >>> not sum([not i in A for i in B]) True` `

`len(A) != len(B)`并且在这个例子中`len(A) > len(B)` 。 为了避免这种情况，你可以添加一个语句。

` `>>> not sum([not i in A for i in B]) if len(A) == len(B) else False False` `

` `>>> def foocomprehend(): return not sum([not i in data for i in data2]) >>> min(timeit.repeat('fooset()', 'from __main__ import fooset, foocount, foocomprehend')) 25.2893661496 >>> min(timeit.repeat('foosort()', 'from __main__ import fooset, foocount, foocomprehend')) 94.3974742993 >>> min(timeit.repeat('foocomprehend()', 'from __main__ import fooset, foocount, foocomprehend')) 187.224562545` `

` `def sequences_contain_same_items(a, b): for item in a: try: i = b.index(item) except ValueError: return False b = b[:i] + b[i+1:] return not b` `
• UnicodeDecodeError：'utf8'编解码器无法解码位置3-6中的字节：无效的数据
• 最安全的方法来将浮点数转换为整数在Python中？
• 删除Python unicodestring中的重音符号的最佳方法是什么？
• 打印没有换行（打印'a'）打印空间，如何删除？
• Python 3.x中新的打印函数在Python 2打印语句中的优点是什么？
• UnicodeEncodeError：'ascii'编解码器不能编码字符u'\ xa0'在位置20：序号不在范围内（128）
• 卸载从源代码构build的python？
• 如何保持Python打印不添加换行符或空格？
• 我怎样才能在python的OrderedDict的顶部添加一个元素？
• Python 2.x中的非本地关键字
• 没有名为MySQLdb的模块