Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map lambda x,y with a constant x

Tags:

python

lambda

map

What would be an elegant way to map a two parameter lambda function to a list of values where the first parameter is constant and the second is taken from a list?

Example:

lambda x,y: x+y
x='a'
y=['2','4','8','16']

expected result:

['a2','a4','a8','a16']

Notes:

  • This is just an example, the actual lambda function is more complicated
  • Assume I can't use list comprehension
like image 492
Jonathan Livni Avatar asked Oct 04 '11 12:10

Jonathan Livni


1 Answers

You can use itertools.starmap

a = itertools.starmap(lambda x,y: x+y, zip(itertools.repeat(x), y))
a = list(a)

and you get your desired output.

BTW, both itertools.imap and Python3's map will accept the following:

itertools.imap(lambda x,y: x+y, itertools.repeat(x), y)

The default Python2's map will not stop at the end of y and will insert Nones...


But a comprehension is much better

[x + num for num in y]
like image 165
JBernardo Avatar answered Oct 03 '22 11:10

JBernardo