[英]comparing lists with tuples in python
我有一个包含两个单词的列表
list = ["the","end"]
我有一个这样的元组列表
bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
是否有可能系统地遍历bigramslist中的每个元组,并查看列表中的两个单词是否与bigramlist中的任何元组匹配。 如果是,则返回true?
谢谢
>>> 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指出的那样,使用集合将导致O(1)搜索时间复杂度,其中搜索列表为O(n)。 作为附带说明,创建集合也是一个额外的O(n)。
不确定这是否是您要的:
>>> 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]
>>>
匹配任何比较值-如果该列表包含true,则可以决定要怎么做。
编辑:好的,克里格的方法要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.