向后倒数

时间:2011-05-26 09:55:50

标签: python

我有一个像这样组织的清单:

[('down', 0.0098000000000000309), 
('up', 0.0015000000000000568), 
('down', 0.008900000000000019), 
('down', 0.023300000000000098), 
('down', 0.011599999999999944), 
('down', 0.0027000000000000357), 
('up', 0.0023999999999999577), 
('up', 0.0065000000000000613), 
('down', 0.0057000000000000384), 
('down', 0.018400000000000083), 
('up', 0.009300000000000086), 
('down', 0.0038000000000000256), 
('down', 0.00050000000000005596), 
('up', 0.0082000000000000961), .....

“向后比较”的最佳方法是什么? ,基本上我想要返回“是”(或者其他......)如果我们得到一系列2“下降”后跟一个“向上”并且第二个值低于0.0095。

我希望他有道理..

5 个答案:

答案 0 :(得分:5)

创建一个滑动窗口,并对其进行测试:

def slidingwindow(iterable):
    iterator = iter(iterable)
    first, second = iterator.next(), iterator.next()
    for next in iterator:
        yield (first, second, next)
        first, second = second, next

def testforcondition(data):
    for window in slidingwindow(data):
        direction = [w[0] for w in window]
        if direction == ['down', 'down', 'up'] and window[2][1] < 0.0095:
            return True
    return False

答案 1 :(得分:3)

你走了:

def frob(l):
    downcount = 0
    for ele in l:
        if downcount >= 2 and ele[0] == 'up' and ele[1] < 0.0095:
                return True
        downcount = (downcount + 1) if ele[0] == 'down' else 0
    return False

答案 2 :(得分:0)

这是我的尝试:

def test(data):
  for x in xrange(2, len(data)):
    if data[x-2][0] is 'down' and data[x][x-1] is 'down' and data[x][0] is 'up' and data[x][1] < 0.0095:
      return True
  return False

答案 3 :(得分:0)

我的建议(虽然现在有了第三个片段,但这不再是真的了):

def compback(l):
    return any(i1[0] == i2[0] == "down" 
               and i2[1] < 0.0095
               and i3[0] == "up"
               for i1, i2, i3 in zip(l, l[1:], l[2:]))

答案 4 :(得分:0)

for index in xrange(0, len(list) - 2):
    if list[index][0] == 'down' and list[index + 1][0] == 'down' and list[index + 2][0] == 'up' and list[index + 1][1] < 0.0095:
         return True