dic_list = [{'a': '123456789',
'b': '',
'c': '1',
'd': '',
'e': '',
'f': '',
'e': '',
'g': '',
'h': '',
'Total': '1'}, {'a': '123456710',
'b': '',
'c': '1',
'd': '',
'e': '',
'f': '',
'e': '',
'g': '',
'h': '',
'Total': '1'}, ...]
我想把上面的字典做成下面的字典形式。有很多词典,而不仅仅是上面的词典。实际上,当我写“ type(dict_list)”时,它说的是列表。我不知道为什么说清单。我也想得到“皮尔逊相关系数”。
dic_list = {'123456789': {
'b': '',
'c': 1,
'd': '',
'e': '',
'f': '',
'g': '',
'h': '',
'i': '',
'Total': '1',},
{'123456710': {
'b': '',
'c': 1,
'd': '',
'e': '',
'f': '',
'g': '',
'h': '',
'i': '',
'Total': '1',}....,
答案 0 :(得分:1)
使用Python3.6和字典理解
data() {
return { user: null }
},
created() {
this.user = fetchUser(this.$route.params.id)
}
答案 1 :(得分:0)
据我所知,这应该有效。测试一下,让我知道。
big_dict = {}
for i in dic_list:
k = i['a']
del i['a']
big_dict[k] = dict(i)
print(big_dict)
答案 2 :(得分:0)
如果您确定a
中每个字典中dic_list
中的所有值都是唯一的,则可以按以下方式使用dict理解
>>> from copy import deepcopy
>>> customer = {x.pop('a'):x for x in deepcopy(dic_list)}
>>> print(customer)
{'123456789': {'b': '', 'c': '1', 'd': '', 'e': '', 'f': '', 'g': '', 'h': '', 'Total': '1'},
'123456710': {'b': '', 'c': '1', 'd': '', 'e': '', 'f': '', 'g': '', 'h': '', 'Total': '1'}}
如果您不进行深拷贝,则原始列表将被修改
编辑:皮尔逊相关性
import math
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def sim_pearson(data, name1, name2):
X = [v for k,v in data.get(name1).items() if k in data.get(name2).keys()]
Y = [v for k,v in data.get(name2).items() if k in data.get(name1).keys()]
# convert string to float if convertable, else replace with zero
X = [float(i) if isfloat(i) else 0 for i in X]
Y = [float(i) if isfloat(i) else 0 for i in Y]
count = len(X)
sumX = sum(X)
sumY = sum(Y)
sumPowX = sum([i**2 for i in X])
sumPowy = sum([i**2 for i in Y])
sumXY = sum([i*j for i,j in zip(X,Y)])
return ( sumXY- ((sumX*sumY)/count) )/ math.sqrt( (sumPowX - (pow(sumX,2) / count)) * (sumPowy - (pow(sumY,2)/count)))
sim_pearson(customer,'123456789','123456710')
# here 'customer' is the dictionary you have created earlier
您可以使用scipy.stats.pearsonr
计算Pearson相关系数