我有元组列表,每个元组都有元素长度。我使用以下代码来计算元素的偏移量,具体取决于早期元素的长度。
import pprint
recordInfo = [(3,), (4,), (1,), (2,)] # List of lengths
# Calculate and add offsets
recordSize = 0
for index, info in enumerate(recordInfo):
recordInfo[index] = info + ( recordSize, ) # Replace with new tuple with offset
recordSize += info[0] # Calculate next offset
pprint.pprint(recordInfo)
输出
[(3, 0), (4, 3), (1, 7), (2, 8)]
有没有办法以函数形式进行循环,比如列表理解?我无法弄清楚如何避免临时变量recordSize
,这使得它变得不可能?
答案 0 :(得分:2)
它不漂亮,而且效率不高,但这里有一个列表理解能够满足您的要求:
>>> recordInfo = [(3,), (4,), (1,), (2,)]
>>> [info + (sum(_info[0] for _info in recordInfo[:i]),)
for i,info in enumerate(recordInfo)]
[(3, 0), (4, 3), (1, 7), (2, 8)]
它的工作原理是在每次迭代时重新计算当前项目的偏移量,因此效率很低。
它适用于Python 2& 3。
答案 1 :(得分:2)
>>> recordInfo = [3, 4, 1, 2]
>>> from functools import reduce
>>> reduce(lambda x, y: x + [(y, sum(x[-1]))], recordInfo, [(0, 0)])[1:]
[(3, 0), (4, 3), (1, 7), (2, 8)]
>>> from itertools import accumulate
>>> list(zip(recordInfo, [0] + list(accumulate(recordInfo))))
[(3, 0), (4, 3), (1, 7), (2, 8)]
如果你有元组:
>>> recordInfo = [(3, 'a'), (4, 'b'), (1, 'c'), (2, 'd')]
>>> reduce(lambda x, y: x + [y + (x[-1][0] + x[-1][-1], )], recordInfo, [(0, )])[1:]
[(3, 'a', 0), (4, 'b', 3), (1, 'c', 7), (2, 'd', 8)]
>>> from operator import itemgetter
>>> [x + (c,) for x, c in zip(recordInfo, accumulate(map(itemgetter(0), [(0,)] + recordInfo)))]
[(3, 'a', 0), (4, 'b', 3), (1, 'c', 7), (2, 'd', 8)]
答案 2 :(得分:1)
可能不是你的功能,但嘿,总是很有趣。
def increment_record(records, size=0):
if not records:
return []
return [(records[0], size)] + increment_record(records[1:], size=size+records[0])
但是,我不认为这是一个模式python,它允许一个人以一种没有本地状态的方式进行寻址(除非你当然使用像前面提到的隐藏状态的上述itertools.aggregate这样的高级函数) 。当然,如果你真的需要,你可以定义某种计数对象(或使用闭包)。
class Tallier(object):
def __init__(self, val):
self._val = val
def tally(self, new_val):
old_val = self._val
self._val += new_val
return old_val
[(val, tallier.tally(val)) for val in values]