递增增加列表中的非零元素

时间:2019-01-04 00:16:48

标签: python list

如果我有此列表

a = [1,0,0,1,0,0,0,1]

我希望它变成

a = [1,0,0,2,0,0,0,3]

6 个答案:

答案 0 :(得分:5)

解决方案#1和#2的设置

from itertools import count

to_add = count()
a = [1,0,0,1,0,0,0,1]

解决方案#1

>>> [x + next(to_add) if x else x for x in a]
[1, 0, 0, 2, 0, 0, 0, 3]

解决方案2 ,,,但有趣

>>> [x and x + next(to_add) for x in a]
[1, 0, 0, 2, 0, 0, 0, 3]

解决方案#3和#4的设置

import numpy as np
a = np.array([1,0,0,1,0,0,0,1])

解决方案3

>>> np.where(a == 0, 0, a.cumsum())
array([1, 0, 0, 2, 0, 0, 0, 3])

解决方案4(我最喜欢的解决方案)

>>> a*a.cumsum()
array([1, 0, 0, 2, 0, 0, 0, 3])

所有cumsum解决方案都假设a的非零元素都是1。


时间:

# setup
>>> a = [1, 0, 0, 1, 0, 0, 0, 1]*1000
>>> arr = np.array(a)
>>> to_add1, to_add2 = count(), count()
# IPython timings @ i5-6200U CPU @ 2.30GHz (though only relative times are of interest)
>>> %timeit [x + next(to_add1) if x else x for x in a] # solution 1
669 µs ± 3.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit [x and x + next(to_add2) for x in a] # solution 2
673 µs ± 15.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit np.where(arr == 0, 0, arr.cumsum()) # solution 3
34.7 µs ± 94.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit arr = np.array(a); np.where(arr == 0, 0, arr.cumsum()) # solution 3 with array creation
474 µs ± 14.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit arr*arr.cumsum() # solution 4
23.6 µs ± 131 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit arr = np.array(a); arr*arr.cumsum() # solution 4 with array creation
465 µs ± 6.82 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

答案 1 :(得分:3)

这是我要怎么做:

def increase(l):
    count = 0
    for num in l:
        if num == 1:
            yield num + count
            count += 1
        else:
            yield num

c = list(increase(a))

c

[1, 0, 0, 2, 0, 0, 0, 3]

答案 2 :(得分:1)

为此使用列表理解:

print([a[i]+a[:i].count(1) if a[i]==1 else a[i] for i in range(len(a))])

输出:

[1, 0, 0, 2, 0, 0, 0, 3]

循环版本:

for i in range(len(a)):
    if a[i]==1:
        a[i]=a[i]+a[:i].count(1)

答案 3 :(得分:1)

因此,您想增加除第一个# Change filename to whatever you want. filename = "fig4" # LaTeX amsmath and utf8 input support. set terminal cairolatex size 9cm,9cm color colortext standalone lw 4 header \ "\\usepackage{amsmath}\ \\usepackage[utf8]{inputenc}" # Don't change output name set output "gptemp.tex" unset key splot 'data.dat' with boxes set out system sprintf("pdflatex\ -interaction batchmode gptemp.tex &&\ mv gptemp.pdf %s.pdf &&\ rm -f gptemp*", filename) 之外的其他所有内容,对吧?

怎么样:

1

或者,如果您愿意:

a = [1,0,0,1,0,0,0,1]

current_number = 0

for i, num in enumerate(a):
    if num == 1:
        a[i] = current_number + 1
        current_number += 1

print(a)

>>> [1, 0, 0, 2, 0, 0, 0, 3]

答案 4 :(得分:0)

使用numpy求和或累积和将1替换为1的总和

4200

答案 5 :(得分:0)

其他选项:一个班轮名单理解,没有依赖性。

[ 0 if e == 0 else sum(a[:i+1]) for i, e in enumerate(a) ]

#=> [1, 0, 0, 2, 0, 0, 0, 3]