假设我有一个清单:
ls = [1,2,4,3,6,18,10,60,70,40]
我想改为:
ls = [1,2,4,3,6,18,10,None,None,40]
因为:
1)索引“x + 1”中的值大于5次的值比索引“x”中的值。
(指数7:60 ,大于指数6:10 乘以 5 )
2)索引“x + 2”中的下一个值也比索引“x”中的值大5倍
(指数8:70 ,大于指数6:10 乘以 5 )
3)索引“x + 3”中的值不大于
(指数9:40 ,不大于指数6:10 乘以 5 )
4)正确条件(“x + 1”和“x + 2”)之间的索引的两个值将被替换为两者之间的无与条件匹配的“限制”(“x”和“x + 3”),因此将“x + 1”和“x + 2”设置为无。
请注意,现在条件不在两个连续索引之间...
这是我尝试过的,虽然看起来“太多了”......
ls = [1,2,4,3,6,18,10,60,70,40]
for i in range (1,len(ls)-1):
if ls[i-1] == None:
# another for to get previous results????
for o in range(0,i):
if ls[o] != None:
lastGood = ls[o]
else:
if ls[i] > ls[i-1]*5:
ls[i] = None
else:
lastGood = ls[i-1]
if ls[i] < ls[i-1]/5:
ls[i] = None
else:
lastGood = ls[i-1]
if ls[i] > lastGood*5:
ls[i] = None
if ls[i] < lastGood/5:
ls[i] = None
print ls
-
output: [1, 2, 4, 3, 6, 18, 10, None, None, 40]
提前致谢!
答案 0 :(得分:1)
我必须同意你所写的代码对你所要求的目的有点多。我设法将其截断一点,这是否解决了您的问题?
lastGoodIndex = 0
for i in range(len(ls) - 1):
if ls[i] == None:
if ls[i+1] > ls[lastGoodIndex]*5:
ls[i+1] = None
elif ls[i+1] > ls[i]*5:
ls[i+1] = None
lastGoodIndex = i
答案 1 :(得分:0)
除了BadKarma找到的好解决方案之外,我还有另一个可能的答案,就是我在挖掘了很长时间之后发现的:
import bisect
from itertools import groupby
from operator import itemgetter
for entry in range(1,len(ls)+1):
startNone = [next(group) for key, group in groupby(enumerate(ls), key=itemgetter(1)) if key == None]
endNone = [next(group) for key, group in groupby(enumerate(reversed(ls)), key=itemgetter(1)) if key == None]
if len(startNone)>0:
if entry-1 > len(ls)-endNone[0][0]:
bigger = ls[entry-2]*5
else:
bigger = ls[startNone[-1][0]-1]*5
else:
bigger = ls[entry-2]*5
seek = ls[0:entry]
i = bisect.bisect_left(seek, bigger)
if i<entry:
ls[entry-1] = None