如何通过每个元素的总和来聚合列表值

时间:2016-11-17 19:50:32

标签: python scripting

我有两个清单
people_ids = ['123','456','123','567'] no_of_steps = [15,16,10,15]
期望的结果:
123人已经采取了25(15 + 10)步骤 456人采取了16步骤 567人采取了15步。

我能够通过Pandas Group的功能来实现它。任何人都可以建议没有任何模块的Python代码吗?

提前致谢:)

6 个答案:

答案 0 :(得分:2)

您可以使用collections.defaultdict()

from collections import defaultdict

d = defaultdict(int)
for j, id in enumerate(people_ids):
    d[id] += no_of_steps[j]

# defaultdict(int, {'123': 25, '456': 16, '567': 15})

答案 1 :(得分:2)

不按要求使用任何模块。

# make a dict of the people
d = {k:0 for k in set(people_ids)}

# populate it with the values
for i in xrange(len(no_of_steps)):
    d[people_ids[i]] += no_of_steps[i]

答案 2 :(得分:2)

你也可以在python中使用groupby

from itertools import groupby
people_ids = ['123', '456', '123', '567']
no_of_steps = [15, 16, 10, 15]

data = sorted(zip(people_ids, no_of_steps))
for people_id, it in groupby(data, key=lambda _: _[0]):
    print('person {} has taken {} steps'.format(people_id, sum(_[1] for _ in it)))

结果:

person 123 has taken 25 steps
person 456 has taken 16 steps
person 567 has taken 15 steps

答案 3 :(得分:0)

以下是最简单的方法:

# your data.
people_ids = ['123','456','123','567']
no_of_steps = [15,16,10,15]

# create a dictionary.
d = {}

# loop through every element of people_ids.
for i in range(len(people_ids)):

    # if element is not present id dictionary, then add it to dict and set its value to no_of_steps[i].
    if people_ids[i] not in d:
        d[people_ids[i]] = no_of_steps[i]
   # if value already present then add value of no_of_steps[i] in current value.
    else:
        d[people_ids[i]] += no_of_steps[i]

# for printing in the order of elements present in people_ids.
# loop through every element present in people_ids.
for i in people_ids:
    # if value is present in dict, print it.
    if i in d:
        print('person {} has taken {} steps'.format(i, d[i]))
         # remove the value so that it wont get printed again.
        del d[i]

答案 4 :(得分:0)

people_ids = ['123','456','123','567']
no_of_steps = [15, 16, 10, 15]

results = {}

for person, steps in zip(people_ids, no_of_steps):
    try:
        results[person] += steps
    except KeyError:
        results[person] = steps

答案 5 :(得分:0)

不使用任何外部模块,也打印输出:

people_ids = ['123','456','123','567']
no_of_steps = [15,16,10,15]

people_ids_dict = {}
for index,id_ in enumerate(people_ids):
    if id_ not in people_ids_dict.keys():
        people_ids_dict[id_] = []
    people_ids_dict[id_].append(no_of_steps[index])

# If you're using python 2
#for key,value in people_ids_dict.iteritems():
for key,val in people_ids_dict.items():
    num_steps =  str(sum(val)) + '(' + '+'.join([str(x) for x in val]) + ')' if len(val) > 1 else str(sum(val))
    print('person {0} has taken {1} steps'.format(key,num_steps))

输出:

person 567 has taken 15 steps
person 456 has taken 16 steps
person 123 has taken 25(15+10) steps