【问题标题】:Counting backwards倒数
【发布时间】:2011-09-02 11:07:39
【问题描述】:

我有一个这样组织的列表:

[('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。

我希望他说得通..

【问题讨论】:

  • This question 展示了如何使用滑动窗口遍历列表。其余的应该很简单。

标签: python


【解决方案1】:

这是我的尝试:

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

【讨论】:

  • 两个 'down' 值之后的 'up' 测试在哪里?
【解决方案2】:

我的建议(虽然现在有了第三片,这已经不是很漂亮了):

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:]))

【讨论】:

  • 这里相同:在两个 'down' 值之后对 'up' 的测试在哪里?
  • @Martijn Pieters:我完全忽略了这一点。我现在已经相应地编辑了我的答案。
【解决方案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

【讨论】:

    【解决方案4】:

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

    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
    

    【讨论】:

    • 但更具可读性! :-) 即使滑动窗口函数存在于一个实用程序模块中,我也能够在一年后的瞬间猜出 testforcondition 函数在做什么。
    • 只是为了表明,可读性通常是一种主观质量。
    • 我猜,可维护性也是主观的。
    【解决方案5】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2015-12-05
      • 2019-05-16
      相关资源
      最近更新 更多