我在python中工作。我有一个名为data.txt的文件,其中包含
John:80,Emily:89,Smith:85,Josh:45,Watson:60
我需要将这些数据放入字典中,然后找到值的最大值,最小值和平均值。我如何从这里创建字典?
这是我到目前为止的代码:
f= open('names.txt', 'r')
lines = f.readlines()
matrix = []
for line in lines:
items = line.strip().split(',')
print items
答案 0 :(得分:1)
我们走了:
>>> data = 'John:80,Emily:89,Smith:85,Josh:45,Watson:60'
>>> pairs = data.split(',')
>>> pairs
['John:80', 'Emily:89', 'Smith:85', 'Josh:45', 'Watson:60']
>>> cast = lambda x: (x[0], int(x[1]))
>>> d = dict(map(lambda x: cast(x.split(':')), pairs))
>>> d
{'Josh': 45, 'Watson': 60, 'John': 80, 'Smith': 85, 'Emily': 89}
>>> max(d.values())
89
>>> min(d.values())
45
>>> float(sum(d.values())) / len(d)
71.8
从文件中读取数据:
with open('data.txt') as f:
data = f.read()
当然,您必须使用边缘情况检查来更新此代码,例如空数据,错误输入,空字典等。
答案 1 :(得分:0)
试试这个:
import csv
reader = csv.reader(open('data.txt', 'r'))
dic = {}
for row in reader:
key, value = row.split(':')
dic[key] = int(value)
print dic
答案 2 :(得分:0)
你去..以下代码也处理2个经典问题:重复条目和空名称条目。
txt=open('data.txt','r').read()
dic={}
mink,minv,maxk,maxv=None,None,None,None
# Populate dictionary 'dic' and calculate max and min values on the fly:
for entry in txt.split(','):
k,v=entry.split(':')
v = int(v)
if len(k)==0: continue
dic[k]=v
if not mink or v < minv : mink,minv = k,v
if not maxk or v > maxv : maxk,maxv = k,v
# Compute average in second loop in case duplicate entries in 1st loop:
avg=0
for v in dic.values(): avg = avg + v
if len(dic)>0 : avg = avg / len(dic)
print dic
print "Min:", mink, minv
print "Max:", maxk, maxv
print "Average:", avg
答案 3 :(得分:0)
data = "John:80,Emily:89,Smith:85,Josh:45,Watson:60"
# alternative for data from file:
# data = open("file.txt").read().strip()
# split the data on every "," and ":" and convert the second value on each pair to an int.
data_dict = dict()
for entry in data.split(","):
key, value = entry.split(":")
data_dict[key] = int(value)
# dict() can take that array of two-element tuples (or lists) and parse it itself so the four lines above can be written as:
data_dict = dict(map(lambda person: (person[0], int(person[1])), [entry.split(":") for entry in data.split(",")]))
# smallest and biggest values:
min(data_dict.values()) # returns 45
max(data_dict.values()) # returns 89
# smallest and biggest key-value pairs:
min(data_dict.iteritems(), key=lambda x:x[1]) # returns ('Josh', '45')
max(data_dict.iteritems(), key=lambda x:x[1]) # returns ('Emily', '89')
# average value (check length != 0 first)
avg = sum(data_dict.values()) / float(len(data_dict)) # returns 71.8
# entry that is nearest to the average (dict needs at least one value)
nearest = data_dict.items()[0]
for key, value in data_dict.iteritems():
if abs(value - avg) < nearest[1]:
nearest = (key, value)
# nearest is ('Emily', 89)