0

大家好,如果您可以以任何方式提供帮助,请提供一些帮助。

我有数据集

Name, Age, 

Mark, 19, 
John, 19, 
Jess, 25, 
Jonty, 21, 

我运行一个计算来比较工作距离以获得这些数据

上班距离(公里) 20 25 30 40

我想要做的是将这些关联回每个名称。我是使用列表还是类结构来做到这一点?这是我想要的输出。

Mark, 19, 20
John, 19, 25
Jess, 25, 30
Jonty, 21, 40

其次,我想知道是否可以比较这些值并做出平均值假设我有一个maxdist = 35

是否可以编写将所有这些距离与最大距离进行比较,然后取出现的值。

Mark, 19, 20
John, 19, 25
Jess, 25, 30

并计算平均年龄??即得到21??

4

2 回答 2

0

另一种做法:

people = \
[
    {"name": "Mark", "Age" : 19, "Distance" : 20},
    {"name": "John", "Age" : 19, "Distance" : 25},
    {"name": "Jess", "Age" : 25, "Distance" : 30},
    {"name": "Jonty", "Age" : 21, "Distance" : 40}
]

avg_dist = sum([person["Distance"] for person in people])/len(people)
print "Average Distance: %d" % avg_dist

lt_dist_filter = lambda dist: lambda x: x["Distance"] < dist
lt_35 = filter(lt_dist_filter(35), people)
print lt_35

avg_age = sum([person["Age"] for person in people])/len(people)
print "Average Age: %d" % avg_age
于 2013-07-15T04:54:21.083 回答
0

假设它们总是按相同的顺序,你可以做一些像这样粗暴的事情——我会说类是一种矫枉过正:

>>> people = [
... ('Mark', 19,) ,
... ('John', 19, ),
... ('Jess', 25, ),
... ('Jonty', 21,)]
>>>
>>> to_work = map(int, '20 25 30 40'.split())
>>> result = []
>>> ages = []
>>> for index, person in enumerate(people):
...     name, age = person
...     result.append((name, age, to_work[index]))
...     ages.append(age)
...
>>> print '\n'.join(map(str, result))
('Mark', 19, 20)
('John', 19, 25)
('Jess', 25, 30)
('Jonty', 21, 40)
>>> print 'max dist =', max(to_work)
max dist = 40
>>> print 'avg. age =', sum(ages) / len(ages)
avg. age = 21
于 2013-07-15T04:53:23.347 回答