如何使列表索引可互换,如['a','b','c']==['b','a','c']?

2024-03-29 02:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

因为['a','b','c']和['b','a','c']有相同的元素,但是python中的['a','b','c']==['b','a','c']test返回False。你知道吗

我知道这是由于索引序列。但是如何让python认识到列表中的元素实际上是相同的呢?你知道吗

下面是一个我没有通过测试的例子:

def wordset(wordlist):
"""Return a set of words found in wordlist."""
wordset = []
for i in range(len(wordlist)):
    if wordlist[i] not in wordset:
        wordset.append(wordlist[i])
return wordset

In: wordset(['now', 'is', 'time', 'is', 'now', 'is', 'is']) == ['is', 'now', 'time']
Out: False

Tags: intestfalse元素列表returntimeis
3条回答

如果您想检查两个列表是否具有相同的元素和相同的出现次数我建议您使用收款台https://docs.python.org/2/library/collections.html#collections.Counter

def are_equal(list_a, list_b):
    return Counter(list_a) == Counter(list_b)

您也可以像一些人建议的那样使用set,但是您将丢失列表中的所有重复项,因此set(['a', 'b', 'b']) == set(['b', 'a'])实际上将返回True

无法创建同时等于['a', 'b', 'c']['b', 'a', 'c']的常规列表。如果需要特殊的语义来进行==比较,则可能需要编写自己的类型:

class wordset(object):
    def __init__(self, words):
        self.words = set(words)

    def __eq__(self, other):
        if isinstance(other, wordset):
            return self.words == other.words
        return self.words == set(other)

不确定这是否真的可以作为一个答案,但是如果你只是想检查两个列表之间是否相等,你可以做一些事情。你知道吗

对于列表list1list2

使用set

set(list1) == set(list2)

使用sorted,对多个循环元素无效

sorted(list1) == sorted(list2)

使用all

all(x in list2 for x in list1):

使用any

not any(x for x in list2 if x not in list1)

相关问题 更多 >