在Python中比较列表和元组
我有一个包含两个单词的列表
list = ["the","end"]
我有一个这样的元组列表
bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
有没有办法系统地检查一下大字母列表中的每个元组,看看列表中的两个单词是否和大字母列表中的任何一个元组匹配?如果匹配的话,返回真(true)?
谢谢
2 个回答
0
不确定这是不是你想要的:
>>> list = ["the", "end"]
>>> bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
>>> def check(list, biglist):
... return [(list[0], list[1]) == big for big in biglist]
...
>>> check(list, bigramslist)
[True, False, False, False]
>>>
这个可以匹配你比较的任何值——你可以根据这个列表是否包含“真”来决定接下来要做什么。
补充:好的,kriegar的方法要好得多。
13
>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True
>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
>>> L1 = ["the","end"]
>>> tuple(L1) in bigramsset
True
补充一下完整性:
正如jsbueno所指出的,使用集合(set)进行查找的时间复杂度是O(1),也就是说查找速度很快。而如果你用列表(list)来查找,时间复杂度是O(n),也就是查找速度会比较慢。顺便提一下,创建集合的过程也是需要O(n)的时间。