代码之家  ›  专栏  ›  技术社区  ›  ca9163d9

多次迭代筛选对象未获得正确的值

  •  0
  • ca9163d9  · 技术社区  · 4 年前

    以下代码得到正确答案,因为 list() 在分配给之前调用 b . max(b) list

    a = map(lambda x: (x[0]*10 + x[1], x[2]*10 + x[3]), aLongList)
    b = list(filter(lambda x: x[0] < 24 and x[1] < 60, a)) # convert to a list
    if not any(b):
        #.... omitted
    max(b)
    

    这是不是一种不用创建列表就能得到正确结果的方法(如果列表很大的话)?


    以下代码

    def perm(A):
        for i,x in enumerate(A):
            for j,y in enumerate(A):
                if i == j: continue
                for k,z in enumerate(A):
                    if i == k or j == k: continue
                    for l,a in enumerate(A):
                        if l == i or l == j or l == k: continue
                        yield [A[i], A[j], A[k], A[l]]
    
    a = map(lambda x: (x[0]*10 + x[1], x[2]*10 + x[3]), perm([1,9,6,0]))
    b = (filter(lambda x: x[0] < 24 and x[1] < 60, a)) # Removed list, so b is a filter obj instead of list
    
    if not any(b):
        pass
    max(b)
    

    退货 (16, 9) 而不是 (19, 6) .

    0 回复  |  直到 4 年前
        1
  •  1
  •   Chris    4 年前

    itertools.tee .

    从单个iterable返回n个独立迭代器。

    from itertools import tee
    
    b1, b2 = tee(filter(lambda x: x[0] < 24 and x[1] < 60, a), 2)
    
    if not any(b1):
        pass
    max(b2)
    

    (19, 6)