Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中比较列表和元组_Python_List_Tuples - Fatal编程技术网

在python中比较列表和元组

在python中比较列表和元组,python,list,tuples,Python,List,Tuples,我有一个包含两个单词的列表 list = ["the","end"] 我有一个这样的元组列表 bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ] 是否可以系统地检查bigramslist中的每个元组,并查看列表中的两个单词是否与bigramslist中的任何元组匹配。如果是这样,返回真值 谢谢 编辑以确保完整性: >>> bigramsset = set( [ (

我有一个包含两个单词的列表

list =  ["the","end"]
我有一个这样的元组列表

bigramslist = [ ("the", "end"), ("end", "of"), ("of", "the"), ("the", "world") ]
是否可以系统地检查bigramslist中的每个元组,并查看列表中的两个单词是否与bigramslist中的任何元组匹配。如果是这样,返回真值

谢谢

编辑以确保完整性:

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

编辑以确保完整性:

>>> 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,则可以决定要执行的操作


编辑:好的,克里加的方法要好得多。

不确定这是否是你想要的:

>>> 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,则可以决定要执行的操作


编辑:好的,克里加的方法要好得多。

你在找重复的吗?是(end,of)匹配(of,end),还是元组必须以相同的顺序匹配?是的,元组必须以相同的顺序匹配你在找重复的吗?是(end,of)匹配(of,end),或者元组必须以相同的顺序匹配吗?是的,元组必须以相同的顺序匹配如果bigramslist中的顺序不重要,它应该是一个
集合而不是一个列表-这将大大加快比较。在使用
操作符中的
检查容器之前,只需执行
bigramslist=set(bigramslist)
。@jsbueno:的确,虽然通常您可以先构造一个集合,而不是构建一个列表,然后再从中构建一个集合。如果bigramslist中的顺序无关紧要,它应该是一个
集合
而不是一个列表-这将大大加快比较速度。在使用
操作符中的
检查容器之前,只需执行
bigramslist=set(bigramslist)
。@jsbueno:的确,虽然通常您可以首先构造一个集合,而不是构建一个列表,然后再从中构建一个集合。