【发布时间】:2017-04-01 02:18:15
【问题描述】:
我正在尝试对齐两个列表中的单词
sentence1 = ['boy','motorcycle','people','play']
sentence2 = ['run','boy','people','boy','play','play']
这是我的代码:
def identicalWordsIndex(self, sentence1, sentence2):
identical_index = []
for i in xrange(len(sentence1)):
for j in xrange(len(sentence2)):
if sentence1[i] == sentence2[j]:
idenNew1 = [i,j]
identical_index.append(idenNew1)
if sentence2[j] == sentence1[i]:
idenNew2 = [j,i]
identical_index.append(idenNew2)
return identical_index
我要做的是从 sentence1 和 sentence2 中获取对齐单词的索引号。
1st 是从 sentence1 到 sentence2 的对齐词索引。 第二个是从 sentence2 到 sentence1 的对齐词索引。
但是上面代码的结果是这样的:
1st : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
2nd : [[0, 1], [1, 0], [0, 3], [3, 0], [2, 2], [2, 2], [3, 4], [4, 3], [3, 5], [5, 3]]
我对结果的期望是这样的:
1st : [[0,1],[2,2],[3,4]]
2nd : [[1,0],[2,2],[3,0],[4,3],[5,3]]
谁能解决?谢谢
【问题讨论】:
-
len(sentence1, sentence2)应该返回类型错误,因为len接受一个参数。你的代码还有一个IndentationError。 -
对不起,我打错了,因为我再次从源代码中重新输入了它。我编辑了,结果还是一样
-
结果并没有变成我期望的那样。它仍然与我上面的代码相同
标签: python list for-loop alignment sentence