2017-04-06 49 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(..))'更多的是浪費週期。 –