我有这个字典并将该数据有效:名单按在字典解析键值 - Python的
In [40]:
atemp
Out[40]:
{0: ['adc telecommunications inc'],
1: ['aflac inc'],
2: ['agco corporation'],
3: ['agl resources inc'],
4: ['invesco ltd'],
5: ['ak steel holding corporation'],
6: ['amn healthcare services inc'],
7: ['amr corporation']}
In [42]:
cemptemp
Out[42]:
Company name nstandar
0 1-800-FLOWERS.COM 1800flowerscom
1 1347 PROPERTY INS HLDGS INC 1347 property ins hldgs inc
2 1ST CAPITAL BANK 1st capital bank
3 1ST CENTURY BANCSHARES INC 1st century bancshares inc
4 1ST CONSTITUTION BANCORP 1st constitution bancorp
5 1ST ENTERPRISE BANK 1st enterprise bank
6 1ST PACIFIC BANCORP 1st pacific bancorp
7 1ST SOURCE CORP 1st source corporation
我的代码,我用的是字典的每个值找到的列nstandar的元素熊猫数据框,其与字典的值的jaccard距离大于0.1并且创建新的字典,其中键是前一个字典的值,并且这些值是基于jaccard距离选择的数据帧的值。
我试过这段代码,但它只是给每个键一个值,我知道我应该有一个每个键的列表。
sd={ y : row['nstandar'] for k,value in atemp.iteritems() for y in value for index , row in cemptemp.iterrows() if jack(y,row['nstandar'])>=0.1}
所以SD是:
{'adc telecommunications inc': '1st century bancshares inc',
'aflac inc': '1st century bancshares inc',
'agco corporation': '1st source corporation',
'agl resources inc': '1st century bancshares inc',
'ak steel holding corporation': '1st source corporation',
'amn healthcare services inc': '1st century bancshares inc',
'amr corporation': '1st source corporation'}
但是,预期输出的第一个关键shuld是:'adc telecommunications inc' :[ '1347 property ins hldgs inc' , '1st century bancshares inc']
那么,怎样才能修复我我的代码来获得我想要什么?
编辑:中捷卡距离的代码是:
def jack(a,b):
x=a.split()
y=b.split()
xy = set(x+y)
return float(len(x)+len(y)-len(xy))/float(len(xy))
编辑2:我想出了一个解决方案:
from collections import defaultdict
td=defaultdict(list)
for k,value in atemp.iteritems():
for y in value:
for index , row in cemptemp.iterrows():
if jack(y,row['nstandar'])>=0.1:
td[y].append(row['nstandar'])
但是,如果尝试写入相同代码但字典理解,它不工作:
from collections import defaultdict
td=defaultdict(list)
td={y : td[y].append(row['nstandar']) for k,value in atemp.iteritems() for y in value for index , row in cemptemp.iterrows() if jack(y,row['nstandar'])>=0.1}
那么,我的解决方案和使用词典理解的代码有什么区别?