3

因此,以下代码读取两个文本文件,两个文本文件都包含 25 行的 25 个整数,并将它们分别放在两个列表中:

num_DIR = '/path/to/num.txt'
den_DIR = '/path/to/den.txt'

def makeList(DIR):
    list = []
    for line in open(DIR).readlines():
            list.append(line.strip())
    return list

num_list = makeList(num_DIR)
den_list = makeList(den_DIR)

输出:

num_list = ['76539', '100441', '108637', '108874', '103580', '91869', '78458', '61955', '46100', '32701', '21111', '13577', '7747', '4455', '2309', '1192', '554', '264', '134', '63', '28', '15', '12', '7', '5']

den_list = ['621266', '496647', '436229', '394595', '353249', '305882', '253983', '199455', '147380', '102872', '67255', '41934', '24506', '13778', '7179', '3646', '1778', '816', '436', '217', '114', '74', '49', '44', '26']

我将如何让两个列表中的每个值都加上它之后的所有值的总和,就像在累积列表中一样?

4

3 回答 3

4

sum如果性能不重要,您还可以使用和列表推导:

>>> num_list=[1,2,3]
>>> [sum(num_list[:y]) for y in range(1, len(num_list) + 1)]
[1, 3, 6]
于 2014-06-18T19:08:33.243 回答
4

您似乎希望在每个元素之后将所有值的总和放在列表末尾

summed=[]
den_list = map(int,den_list)
for i,j in enumerate(den_list[:-1]):
    summed += j,sum(den_list[i+1:])

如果您不想将原始值保留在列表中

summed=[sum(num_list[i+1:])for i,j in enumerate(num_list[:-1])]
于 2014-06-18T19:24:25.663 回答
3

如果您运行的是 python 3.2 或更高版本,电池包含在itertools.accumulate.

如果您正在运行之前的版本,则文档中提供的纯 python 等效项可以等效地工作(尽管不是 C 速度):

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

演示:

from itertools import accumulate

list(accumulate(map(int,num_list)))
Out[3]: 
[76539,
 176980,
 285617,
 394491,
 498071,
 589940,
 668398,
 730353,
 776453,
 809154,
 830265,
 843842,
 #snip...,
 860627
]

请注意,您需要将所有这些字符串转换为ints,就像我对map.

于 2014-06-18T19:09:14.913 回答