Python:如何比较两个列表

时间:2014-05-01 04:39:55

标签: python

最快迭代列表x以检查y中是否列出了任何字符?

x=['cat','dog','fish']
y=['a','b','b']

3 个答案:

答案 0 :(得分:1)

您可以将y转换为一个集合,然后对x进行迭代,看看其中是否有y,就像这样

print any(any(item in word for word in x) for item in set(y))
# True

any在找到匹配后立即发生短路,因此效率非常高。

除此之外,我们可以将它们转换为集合,然后检查它们是否是不相交的集合,如下所示

print not {char for word in x for char in word}.isdisjoint(set(y))
# True

isdisjoint如果确定两个集合都不是不相交的集合,也会短路。

答案 1 :(得分:0)

使用列表理解:

>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> [char in word for char in y for word in x]
[True, False, False, False, False, False, False, False, False]
>>> 

这会打印所有字符和单词的上述输出:True因为'a'位于'cat',其余为False,因为没有其他字符存在。< / p>

以下是一个更易于阅读的示例:

>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> [(word, char, char in word) for char in y for word in x]
[('cat', 'a', True), ('dog', 'a', False), ('fish', 'a', False), ('cat', 'b', False), ('dog', 'b', False), ('fish', 'b', False), ('cat', 'c', True), ('dog', 'c', False), ('fish', 'c', False)]
>>> ["It is %s that %s is in %s" %(str(char in word), char, word) for char in y for word in x]
['It is True that a is in cat', 'It is False that a is in dog', 'It is False that a is in fish', 'It is False that b is in cat', 'It is False that b is in dog', 'It is False that b is in fish', 'It is True that c is in cat', 'It is False that c is in dog', 'It is False that c is in fish']
>>> 

回答你的评论,是的,有道路:

>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> myList = []
>>> [myList.append(word) for word in x for char in y if char in word]
[None, None]
>>> myList
['cat', 'cat']
>>> list(set(myList))
['cat']
>>> 

列表推导打印[None, None]的原因是因为内置方法append()没有返回任何内容,因此None

答案 2 :(得分:0)

为什么这不足以进行比较?

>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> x == y
False
>>> b = ['a','b', 'b']
>>> x == b
False
>>> y == b
True