如何使用 python 按字典的值对文件进行排序
how to sort files by the value of a dictionary using python
file=sorted(file)
词典数据(姓名、平均分数)较早收集并存储在文件中。此代码然后重新打开文件并将其中的数据存储在变量(文件)中。我需要文件中的这些数据按值排序,所以如果文件中的数据是:
詹姆斯:5
蒂姆:8
它将进行排序,以便蒂姆排在首位,因为他的平均得分更高。我将如何去做这件事?
字典也在那里,因此 name 和 score 在排序时保持在一起
import collections
dict = {}
# Assume file format is "name:score" for each line.
with open("classa2.txt", "r") as f:
for line in f:
line = line.split(':')
dict[line[0]] = line[1]
# Sort by value (score)
od = collections.OrderedDict(sorted(dict.items(), key=lambda t: t[1]))
# Write new results
with open("classa2.txt", "w") as f:
for key in od:
f.write(key + ':' + str(od[key]) + "\n")
print key + ":" + str(od[key])
数据文件看起来像
tim: ["4.0", "2.9", "3.4"]
james: ["3.8", "3.8"]
clara: ["2.6", "3.5", "3.2"]
在这种情况下你需要像
这样的东西
from ast import literal_eval
def sort_key(line):
# split "name: scores" into ["name", " scores"]
name, score_str = line.split(":")
# convert " [\"1.9\", \"3.8\"]" into ["1.9", "3.8"]
scores = literal_eval(score_str.strip())
# convert ["1.9", "3.8"] into [1.9, 3.8]
scores = [float(f) for f in scores]
# calculate average score
avg = sum(scores) / len(scores)
return avg
那你可以
# read data from file
with open("classa2.txt") as inf:
lines = [line.rstrip() for line in inf]
# sort highest scores first
lines.sort(key=sort_key, reverse=True)
print("\n".join(lines))
这导致
james: ["3.8", "3.8"]
tim: ["4.0", "2.9", "3.4"]
clara: ["2.6", "3.5", "3.2"]
file=sorted(file)
词典数据(姓名、平均分数)较早收集并存储在文件中。此代码然后重新打开文件并将其中的数据存储在变量(文件)中。我需要文件中的这些数据按值排序,所以如果文件中的数据是: 詹姆斯:5 蒂姆:8 它将进行排序,以便蒂姆排在首位,因为他的平均得分更高。我将如何去做这件事? 字典也在那里,因此 name 和 score 在排序时保持在一起
import collections
dict = {}
# Assume file format is "name:score" for each line.
with open("classa2.txt", "r") as f:
for line in f:
line = line.split(':')
dict[line[0]] = line[1]
# Sort by value (score)
od = collections.OrderedDict(sorted(dict.items(), key=lambda t: t[1]))
# Write new results
with open("classa2.txt", "w") as f:
for key in od:
f.write(key + ':' + str(od[key]) + "\n")
print key + ":" + str(od[key])
数据文件看起来像
tim: ["4.0", "2.9", "3.4"]
james: ["3.8", "3.8"]
clara: ["2.6", "3.5", "3.2"]
在这种情况下你需要像
这样的东西from ast import literal_eval
def sort_key(line):
# split "name: scores" into ["name", " scores"]
name, score_str = line.split(":")
# convert " [\"1.9\", \"3.8\"]" into ["1.9", "3.8"]
scores = literal_eval(score_str.strip())
# convert ["1.9", "3.8"] into [1.9, 3.8]
scores = [float(f) for f in scores]
# calculate average score
avg = sum(scores) / len(scores)
return avg
那你可以
# read data from file
with open("classa2.txt") as inf:
lines = [line.rstrip() for line in inf]
# sort highest scores first
lines.sort(key=sort_key, reverse=True)
print("\n".join(lines))
这导致
james: ["3.8", "3.8"]
tim: ["4.0", "2.9", "3.4"]
clara: ["2.6", "3.5", "3.2"]