简体   繁体   English

元素不为零的列表计算

[英]List calculation with elements not equal to zero

Let's assume I have a list:假设我有一个列表:

list1 = [16620, 22032, 0, 0, 0, 136813, 137899, 0, 199546, 204804]

I am looking for a new list that subtracts every 'non-zero' value from the following 'non-zero' value, eg 22032-16620, 137899-136813.我正在寻找一个新列表,该列表从以下“非零”值中减去每个“非零”值,例如 22032-16620、137899-136813。 'Zero' values will stay untouched. “零”值将保持不变。 In addition to that, the subtracted 'non-zero' value should change to zero.除此之外,减去的“非零”值应更改为零。 The output would look something like:输出将类似于:

list2 = [0, 5412, 0, 0, 0, 0, 1086, 0, 0, 5258]

Please note that the numbers, the length of the list and its distribution of elements may vary, eg a list could also look like请注意,列表的数量、长度及其元素分布可能会有所不同,例如列表也可能看起来像

list1 = [0, 0, 0, 0, 95472, 0, 0, 104538, 0, 0, 0, 0, 187649, 0, 0, 204841, 0, 0, 0, 0, 0, 0, 0, 0]

which should turn into:这应该变成:

list2 = [0, 0, 0, 0, 0, 0, 0, 9066, 0, 0, 0, 0, 0, 0, 0, 17192, 0, 0, 0, 0, 0, 0, 0, 0]

As you can see, the number of elements stays the same for list1 and list2.如您所见,list1 和 list2 的元素数量保持不变。 Also, there is always an even number of 'zero' values and an even number of 'non-zero' values.此外,始终存在偶数个“零”值和偶数个“非零”值。 Help is greatly appreciated!非常感谢帮助!

What I have so far:到目前为止我所拥有的:

from itertools import cycle, chain
list1 = [11545, 15334, 71341, 73861, 0, 0, 170374, 171671]
newlist = [list1[i + 1] - list1[i] for i in range(len(list1)-1)]
list2 = list(chain.from_iterable(zip(newlist[0::2], cycle([int()]))))
print list2

The output print list2 looks like I imagine it to be, yet it won't work for a list that looks like:输出 print list2 看起来像我想象的那样,但它不适用于如下所示的列表:

list1 = [16620, 22032, 0, 0, 0, 136813, 137899, 0, 199546, 204804]

Copy over, but adjust non-zero values, keeping track of the previous one.复制,但调整非零值,跟踪前一个。

list2 = []
prev = None
for curr in list1:
    if curr:
        if prev:
            curr -= prev
            prev = None
        else:
            prev = curr
            curr = 0
    list2.append(curr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM