我有一个零和一个列表,看起来像这样:
lst = [0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]
Run Code Online (Sandbox Code Playgroud)
我怎样才能将这个变换为:
transformed_lst = lst = [0, 1, 1, 1, 1, 0, 0, 0, 2, 2, 0, 0, 0, 3, 0, 4, 4]
Run Code Online (Sandbox Code Playgroud)
基本上,在每次出现1时,将其转换为n + 1整数.我确信使用itertools/groupby/functools有一种优雅的方法.这是一次尝试,但不太正确:
from itertools import cycle
ints = cycle(range(len(lst)))
transformed_lst = [next(ints) if i != 0 in lst else 0 for i in lst]
>>> [0, 0, 1, 2, 3, 0, 0, 0, 4, 5, 0, 0, 0, 6, 0, 7, 8]
Run Code Online (Sandbox Code Playgroud)
你基本上有两种状态 - "读取0s"和"读取1s" - 当你在那时(即从1到0)之间切换时,将应用于后续1s更改的增量:
reading_zeroes = True
delta = 0
for x in input:
if x:
reading_zeroes = False
x += delta
elif not reading_zeroes:
delta += 1
reading_zeroes = True
yield x
Run Code Online (Sandbox Code Playgroud)