简体   繁体   English

将列表与python中的元组进行比较

[英]comparing lists with tuples in python

I have a list containing two words 我有一个包含两个单词的列表

list =  ["the","end"]

I have a list of tuples such as this 我有一个这样的元组列表

bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]

Is it possible to systematically go through each tuple in the bigramslist and see if both words in the list match any of the tuples in the bigramlist. 是否有可能系统地遍历bigramslist中的每个元组,并查看列表中的两个单词是否与bigramlist中的任何元组匹配。 And if so return true? 如果是,则返回true?

thanks 谢谢

>>> L1 = ["the","end"]
>>> bigramslist = [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ]
>>> tuple(L1) in bigramslist
True

edit for completeness: 编辑完整性:

>>> bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
>>> L1 = ["the","end"]
>>> tuple(L1) in bigramsset
True

as jsbueno pointed out, using a set will result in a O(1) search time complexity where as searching the list is O(n). 正如jsbueno指出的那样,使用集合将导致O(1)搜索时间复杂度,其中搜索列表为O(n)。 As a side note creating the set is also an additional O(n). 作为附带说明,创建集合也是一个额外的O(n)。

Not sure if this is what you're after: 不确定这是否是您要的:

>>> 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]
>>> 

Matches any of the compared values - you can then decide what to do if that list contains true. 匹配任何比较值-如果该列表包含true,则可以决定要怎么做。

Edit: Ok, kriegar's method is a lot better. 编辑:好的,克里格的方法要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM