Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.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 - Fatal编程技术网

在两个Python列表中查找顺序相同的公共元素

在两个Python列表中查找顺序相同的公共元素,python,list,Python,List,有一个关于python的快速问题。我想知道是否有任何简单的python方法来获取两个列表,例如: a = ['t', 'o', 'a', 'c'] b = ['c', 't', 'a', 'o'] 然后返回两个列表之间相对顺序相同的公共元素/字符 # possible outputs for this list could be either: output: ['t', 'a'] output: ['t', 'o'] 我可以从两个列表开始,提取匹配的元素 在保持秩序的同时,通过这样做: c

有一个关于python的快速问题。我想知道是否有任何简单的python方法来获取两个列表,例如:

a = ['t', 'o', 'a', 'c']
b = ['c', 't', 'a', 'o']
然后返回两个列表之间相对顺序相同的公共元素/字符

# possible outputs for this list could be either:
output: ['t', 'a']
output: ['t', 'o']
我可以从两个列表开始,提取匹配的元素 在保持秩序的同时,通过这样做:

c = ['z', 't', 'o', 'g', 'a', 'c', 'f']
d = ['e', 'q', 'c', 't', 'a', 'o', 'y']
a = [x for x in c if x in d]
b = [x for x in d if x in c]
这将给我原始的a和b列表。然而,我无法找到一个方法来进一步减少这种情况。尝试使用集合,但无法保持元素的顺序。我知道,对于和n^2来说,将一个列表与另一个列表进行比较可能是一种简单的方法,但我正试图避免这种情况,并找到一种解决方案,在两个列表中找到相对最大的匹配项

>>> import itertools
>>> a = ['t', 'o', 'a', 'c']
>>> b = ['c', 't', 'a', 'o']

>>> [i for i in itertools.combinations(a, 2) if i in  itertools.combinations(b, 2)]

[('t', 'o'), ('t', 'a')]
编辑:

全部

>>> c = ['z', 't', 'o', 'x', 'a', 'c', 'f', 'g']
>>> d = ['e', 'q', 'c', 't', 'a', 'g', 'o', 'y']

>>> def f(l):
...  r = []
...  for i in range(2, len(l)+1):
...   r += itertools.combinations(l, i)
...  return r
>>>
>>> [i for i in f(c) if i in f(d)]

[('t', 'o'), ('t', 'a'), ('t', 'g'), ('a', 'g'), ('c', 'g'), ('t', 'a', 'g')]
或:


你试过什么?你也研究过拓扑排序吗?'a'是唯一一个顺序相同的元素,不是吗?@nfnneil,'a'位于相同的位置/索引,我认为OP是在要求元素之间的相对顺序('c'在
a
中在'o'之后,但在
b
中在之前)@nfnneil,如R所述,我试图找到我更新问题的相对顺序。很抱歉。据我所知,这是最重要的。它是NP难的。这是一个众所周知的问题,所以你可以在谷歌上搜索代码样本。你可以通过用文字解释这个想法来改进你的答案。我非常喜欢这个解决方案!然而,在玩了这个之后,我看到for范围将导致像c=['I','t']和d=['m','I','t']这样的列表fail@JackLiaiea对不起,现在试试
>>> def f(l):
...     return [j for i in range(2, len(l)+1) for j in list(itertools.combinations(l, i))]
>>>
>>> [i for i in f(c) if i in f(d)]

[('t', 'o'), ('t', 'a'), ('t', 'g'), ('a', 'g'), ('c', 'g'), ('t', 'a', 'g')]