Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map function to an element in tuple

I have in mind something that I would do in Haskell like this:

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

Is it possible to do such mapping to tuple in Python elegantly (without looking inside f?) The best I could come with was:

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

another possibility is

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

But I like neither solution. I do not like the first one, because it's not a single expression and could not be so easily inlined. The other solution has this property, however it's ugly because it unnecessarily calls f() twice in each iteration. Is it possible to somehow unpack the result inside the iteration?

like image 668
user1747134 Avatar asked Oct 25 '25 21:10

user1747134


1 Answers

Just map lst to f first:

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)) 
like image 169
Martijn Pieters Avatar answered Oct 27 '25 10:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!