我的代码的输出如下:
[{'Total Population:': 4585, 'Total Water Ice Cover': 2.848142234497044, 'Total Developed': 17.205368316575324, 'Total Barren Land': 0.22439908514219134, 'Total Forest': 34.40642126612868},
{'Total Population:': 4751, 'Total Water Ice Cover': 1.047783534830167, 'Total Developed': 37.27115716753022, 'Total Barren Land': 0.11514104778353484, 'Total Forest': 19.11341393206678},
{'Total Population:': 3214, 'Total Water Ice Cover': 0.09166603009701321, 'Total Developed': 23.50469788404247, 'Total Barren Land': 0.2597204186082041, 'Total Forest': 20.418608204109695},
{'Total Population:': 5005, 'Total Water Ice Cover': 0.0, 'Total Developed': 66.37545713124746, 'Total Barren Land': 0.0, 'Total Forest': 10.68671271840715},
...
]
我想要做的是获取“总人口”的所有值并将其存储在一个列表中。然后获取所有“总水冰盖”并将其存储在另一个列表中,依此类推。对于这样的数据结构,如何提取这些值并将它们存储到单独的列表中?
谢谢
最佳答案
如果您的目标是calculate Pearson's correlation ,您应该使用 pandas
来实现此目的。
假设您的原始词典列表存储在名为 output
的变量中。您可以使用以下方法轻松将其转换为 pandas
DataFrame:
import pandas as pd
df = pd.DataFrame(output)
print(df)
# Total Barren Land Total Developed Total Forest Total Population: Total Water Ice Cover
#0 0.224399 17.205368 34.406421 4585 2.848142
#1 0.115141 37.271157 19.113414 4751 1.047784
#2 0.259720 23.504698 20.418608 3214 0.091666
#3 0.000000 66.375457 10.686713 5005 1.047784
现在您可以轻松生成相关矩阵:
# this is just to make the output print nicer
pd.set_option("precision",4) # only show 4 digits
# remove 'Total ' from column names to make printing smaller
df.rename(columns=lambda x: x.replace("Total ", ""), inplace=True)
corr = df.corr(method="pearson")
print(corr)
# Barren Land Developed Forest Population: Water Ice Cover
#Barren Land 1.0000 -0.9579 0.7361 -0.7772 0.4001
#Developed -0.9579 1.0000 -0.8693 0.5736 -0.6194
#Forest 0.7361 -0.8693 1.0000 -0.1575 0.9114
#Population: -0.7772 0.5736 -0.1575 1.0000 0.2612
#Water Ice Cover 0.4001 -0.6194 0.9114 0.2612 1.0000
现在您可以通过键访问各个相关性:
print(corr.loc["Forest", "Water Ice Cover"])
#0.91135717479534217
关于python - 字典列表想要获取每个值并将它们放入单独的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53731864/