如果您可以以任何方式提供帮助,请大家帮忙。
我有数据集
Name, Age,
Mark, 19,
John, 19,
Jess, 25,
Jonty, 21,
我运行一个比较工作距离的计算来获取此数据
工作距离(km) 20 25 三十 40
我想要做的是将这些与每个名称联系起来。我是使用列表还是类结构来做这件事?这是我想要的输出。
Mark, 19, 20
John, 19, 25
Jess, 25, 30
Jonty, 21, 40
其次我想知道是否可以比较这些值并制作一个平均值让我们说我有一个maxdist = 35
可以写入比较所有这些dist到最大距离,然后取出出现的值。
Mark, 19, 20
John, 19, 25
Jess, 25, 30
并计算平均年龄?我得到21 ??
答案 0 :(得分: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
答案 1 :(得分: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