for循环中的意外输出 - Python

时间:2014-04-06 16:52:06

标签: python string list

我有这个清单:

t=[['universitario de deportes'],['lancaster'],['universitario de'],['juan aurich'],['muni'],['juan']]

我想根据jaccard距离重新排序列表。如果我重新排序t,预期的输出应为:

[['universitario de deportes'],['universitario de'],['lancaster'],['juan aurich'],['juan'],['muni']]

jackard距离的代码工作正常,但其余代码没有给出预期的输出。代码如下:

def jack(a,b):
    x=a.split()
    y=b.split()
    k=float(len(set(x)&set(y)))/float(len((set(x) | set(y))))
    return k
t=[['universitario de deportes'],['lancaster'],['universitario de'],['juan aurich'],['muni'],['juan']]

import copy as cp


b=cp.deepcopy(t)

c=[]

while (len(b)>0):
    c.append(b[0][0])
    d=b[0][0]
    del b[0]
    for m in range (0 , len(b)+1):
        if m > len(b):
            break
            if jack(d,b[m][0])>0.3:
                c.append(b[m][0])
                del b[m]

不幸的是,意外的输出是相同的列表:

print c
['universitario de deportes', 'lancaster', 'universitario de', 'juan aurich', 'muni', 'juan']

编辑:

我试图纠正我的代码,但它也没有用,但我更接近预期的输出:

t=[['universitario de deportes'],['lancaster'],['universitario de'],['juan aurich'],['muni'],['juan']]

import copy as cp


b=cp.deepcopy(t)

c=[]

while (len(b)>0):
    c.append(b[0][0])
    d=b[0][0]
    del b[0]
    for m in range(0,len(b)-1):
        if jack(d,b[m][0])>0.3:
            c.append(b[m][0])
            del b[m]

"关闭"输出是:

['universitario de deportes', 'universitario de', 'lancaster', 'juan aurich', 'muni', 'juan']

第二次编辑:

最后,我提出了一个计算速度非常快的解决方案。目前,我将使用该代码订购60,000个名称。代码如下:

t=['universitario de deportes','lancaster','lancaste','juan aurich','lancaster','juan','universitario','juan franco']

import copy as cp


b=cp.deepcopy(t)

c=[]

while (len(b)>0):
    c.append(b[0])
    e=b[0]
    del b[0]
    for val in b:
        if jack(e,val)>0.3:
            c.append(val)
            b.remove(val)

print c
['universitario de deportes', 'universitario', 'lancaster', 'lancaster', 'lancaste', 'juan aurich', 'juan', 'juan franco'

1 个答案:

答案 0 :(得分:1)

首先,不确定为什么你在单项目清单中得到了所有东西,所以我建议先把它弄平:

t = [l[0] for l in t]

这摆脱了各处的额外零索引,意味着你只需要浅拷贝(因为字符串是不可变的)。

其次,代码的最后三行永远不会运行:

if m > len(b):
    break # nothing after this will happen
    if jack(d,b[m][0])>0.3:
       c.append(b[m][0])
       del b[m]

我认为你想要的是:

out = [] # this will be the sorted list
for index, val1 in enumerate(t): # work through each item in the original list
    if val1 not in out: # if we haven't already put this item in the new list
        out.append(val1) # put this item in the new list
    for val2 in t[index+1:]: # search the rest of the list
        if val2 not in out: # if we haven't already put this item in the new list
            jack(val1, val2) > 0.3: # and the new item is close to the current item
                out.append(val2) # add the new item too

这给了我

out == ['universitario de deportes', 'universitario de', 
      'lancaster', 'juan aurich', 'juan', 'muni']

我通常建议使用比abc等更好的变量名称。