2017-04-06 47 views
2

我想到的东西,我会做在Haskell这样的:地图功能,元组的元素

f :: Int -> (Int, Int) 
-- for example: 
f = `divMod` 12 
foo :: [Int] -> (Int, Int) 
foo = map (fmap (+1) . f) 
-- foo [10, 11, 12, 13] = [(0,11),(0,12),(1,1),(1,2)] 

是否有可能做这样的映射在Python典雅,元组(不包括内部f看?)我可以跟最好的是:

def foo(lst): 
    for x in lst: 
    a, b = f(x) 
    yield a, b + 1 

另一种可能性是

def foo(lst): 
    return map(lambda x: (f(x)[0], f(x)[1]+1), lst) 

但我像没有解决方案。我不喜欢第一个,因为它不是一个单一的表达式,也不容易内联。另一种解决方案具有此属性,但它很丑,因为它在每次迭代中不必要地调用f()两次。有没有可能在迭代中解压结果?

回答

2

只是映射lstf第一:

try: 
    # Python 2, forward compatible version of map 
    from future_builtins import map 
except ImportError: 
    # Python 3, map is already an iterator 
    pass 

def foo(lst): 
    return [(fxa, fxb + 1) for fxa, fxb in map(f, lst)] 
    # or a generator expression for lazy evaluation 
    # return ((fxa, fxb + 1) for fxa, fxb in map(f, lst)) 
0

好了,我发现有两个期望的特性的一个解决方案,但它不是很易读:

def foo(lst): 
    return map(lambda a, b: (a, b+1), *zip(*map(f, lst))) 
+1

使其列出iteration' [ (a,b + 1)for a,b in * zip(* map(f,lst))]' – ling7334

+0

为什么需要使用'map()'?为什么不直接使用生成器表达式呢? –

+0

@ ling7334:那时'* zip(* map(..))'更多的是浪费周期。 –