【问题标题】:Find common subsequence in list在列表中查找公共子序列
【发布时间】:2014-05-26 14:37:48
【问题描述】:

如果我有两个列表,例如

list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy'] ,
list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']

我已经浏览了列表:当我看到两个匹配的元素时,开始计数。当我看到另一对不匹配的元素时,停止该计数器并启动另一个。

(sat, sat) I = 1

(on, on) I = 2

(mat, carpet) J = 1

(xx, xx) k = 1

(yy, yy) k = 2

i = 0
for x in list1:
    for y in list2:
        if x == y:
            print (x, y)
            i += 1
        else:
            j = 0
            j += 1
            print (x, y)

【问题讨论】:

  • 您的问题并不完全清楚,您的代码也没有反映您的意图。请解释清楚。另外,为什么这被标记为 nltk?
  • walk along the list: 可能是for item_1, item_2 in zip(list1, list2):
  • 这是一个开始:repl.it/TMz
  • 你能告诉我们根据上面的输入实际输出应该是什么样子吗?

标签: python nltk


【解决方案1】:
>>> from collections import defaultdict
>>>
>>> list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy']
>>> list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']
>>>
>>> var_it = iter('IJKLMNOPQRSTUVWXYZ') # variable candidates
>>> counters = defaultdict(int)
>>> c = next(var_it)
>>> for word1, word2 in zip(list1, list2):
...     if word1 == word2:
...         counters[c] += 1
...     else:
...         if counters: # Prevent counting until first match
...             counters[next(var_it)] = 1
...             c = next(var_it)
...
>>> for var in sorted(counters):
...     print('{}: {}'.format(var, counters[var]))
...
I: 2
J: 1
K: 2

【讨论】:

    【解决方案2】:

    下面的呢:

    def doit(list1, list2):
        lastmatch = -1
        lastunmatch = -1
        for i, x in enumerate(zip(list1, list2)):
            if x[0] == x[1]:
                lastmatch = i                
            else:
                lastunmatch = i
            print abs(lastmatch - lastunmatch)
    

    正在运行:http://ideone.com/xnJWtz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多