Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中对列表中的相关值求和_Python_Python 3.x_Python 2.7_List - Fatal编程技术网

在python中对列表中的相关值求和

在python中对列表中的相关值求和,python,python-3.x,python-2.7,list,Python,Python 3.x,Python 2.7,List,这里是从记录打印的值,我需要根据第二个数字对第一个数字求和。 如果第一个和第二个数字相同,则需要添加第一个数字 record = [[2, 3], [3, 3], [5, 4], [1, 4]] Expected output = [5, 3], [6, 4]] 您应该首先排序,然后对第二个值进行排序 import itertools import operator records = [[2, 3], [3, 3], [5, 4], [1, 4]] records.sort(key=op

这里是从记录打印的值,我需要根据第二个数字对第一个数字求和。 如果第一个和第二个数字相同,则需要添加第一个数字

record = [[2, 3], [3, 3], [5, 4], [1, 4]]

Expected output = [5, 3], [6, 4]]

您应该首先排序,然后对第二个值进行排序

import itertools
import operator

records = [[2, 3], [3, 3], [5, 4], [1, 4]]
records.sort(key=operator.itemgetter(1))
groups = itertools.groupby(records, key=operator.itemgetter(1))
# groups is now a generator that produces the values:
#   (3, [[2, 3], [3, 3]])
#   (4, [[5, 4], [1, 4]])
然后根据结果生成一个列表:

result = [[sum(record[0] for record in records), grpname] for grpname, records in groups]
算法: 1.根据内部列表中的第二个元素对列表进行排序。 2.合并具有与第二个元素相同值的连续元素

record = [[1,5],[2, 3], [2,5] , [3, 3], [5, 4], [1, 4]]
record.sort(key=lambda x: x[1]) #sorting record according to second value in inner list
length=len(record)
newRecord=[record[0].copy()] #initating newRecording with first value from record
for i in range(1,length):
    if newRecord[-1][1]==record[i][1]:
        #if value of second element is equal than this will execute
        newRecord[-1][0]+=record[i][0]
    else:
        #if value of second element is not equal than this will execute
        newRecord.append(record[i])

print(newRecord)
希望对您有所帮助。

您应该使用。它将易于使用,您无需对任何内容进行排序:

from collections import Counter
record = [[2, 3], [3, 3], [5, 4], [1, 4]]
sums = Counter()
for (value, index) in record:
    sums[index] += value
sums
# Counter({3: 5, 4: 6})

将计数器值转换为所需的输出应该不会太难。

如果您只对求和感兴趣,计数器比groupby更容易使用。这不只是
集合。defaultdict(int)
?我们没有看到任何超酷的
计数器行为。也就是说,它应该比我的sort->groupby方法要快得多:)@AdamSmith:我认为没有任何计数器构造函数可以直接与OP的数据格式一起工作。一种可能是
计数器(k表示(v,k)在记录中表示uu在范围内(v))
但它不可读或效率不高。很好coding@EricDuminil