Python 有一个列表列表,每个元素有一个元组。问题。指定特定元组元素
作为问题行Python 有一个列表列表,每个元素有一个元组。问题。指定特定元组元素,python,distance,edit,Python,Distance,Edit,作为问题行 每个cost[i][j][0]都应该指定第i个cost列表中第j个元组的第一个元素,该元素应该是int,但它表示它们是元组,我不知道为什么。cost[i][j-1][0]是迭代3中的元组。(i=2,j=2,cost[2][1][0]是一个元组)问题在于cost[i][j]=(cost[i-1][j-1],Operation.substitude)。您正在生成一个元组,其第一个元素是元组而不是int;你需要一个额外的[0],就像所有其他情况一样。 def distances(a, b)
每个
cost[i][j][0]
都应该指定第i个cost列表中第j个元组的第一个元素,该元素应该是int,但它表示它们是元组,我不知道为什么。cost[i][j-1][0]
是迭代3中的元组。(i=2,j=2,cost[2][1][0]是一个元组
)问题在于cost[i][j]=(cost[i-1][j-1],Operation.substitude)
。您正在生成一个元组,其第一个元素是元组而不是int;你需要一个额外的[0]
,就像所有其他情况一样。
def distances(a, b):
"""Calculate edit distance from a to b"""
# declare matrix and set top left box to 0 and none
cost = [[(0,0) for x in range(len(a)+1)] for y in range(len(b)+1)]
cost[0][0] = (0, None)
# fill in first row
for i in range(1, len(a)+1):
cost[i][0] = (i, Operation.DELETED)
#fill in first column
for j in range(1, len(b)+1):
cost[0][j] = (j, Operation.INSERTED)
# fill in rest of the table from left to right, one row at a time
i = 1
j = 1
while i < len(a) + 1:
while j < len(b) + 1:
if a[i-1] == b[j-1]:
cost[i][j] = (cost[i-1][j-1], Operation.SUBSTITUTED)
j += 1
else:
subcost = min(cost[i-1][j][0], cost[i][j-1][0], cost[i-1][j-1][0])
if subcost == cost[i-1][j][0]:
cost[i][j] = (cost[i-1][j][0] + 1, Operation.DELETED)
j += 1
elif subcost == cost[i][j-1][0]:
cost[i][j] = (cost[i][j-1][0] + 1, Operation.INSERTED)
j += 1
elif subcost == cost[i-1][j-1][0]:
cost[i][j] = (cost[i-1][j-1][0] + 1, Operation.SUBSTITUTED)
j += 1
i += 1
j = 1
return cost
TypeError: '<' not supported between instances of 'tuple' and 'int'
subcost = min(cost[i-1][j][0], cost[i][j-1][0], cost[i-1][j-1][0])