def change_salary(data: list, amt: int) -> list:
new_data = data[:]
new_data[1] = amt
return new_data
def change_salaries(employees: list, amt: int) -> list:
return list(map(change_salary, employees, [amt]*amt))
employees = [
["Person1", 2000000],
["Person2", 2500000]
]
happier_employees = change_salaries(employees, 100000)
I have the following example code, and I want to add the same increase in salary to all employees in a list. I am trying to work out whether I can use map() with one list and a variable containing an integer to produce the same output as using list comprehension in my change_salaries function:
return [change_salary(employee, amt) for employee in employees]
At the moment, in order for map to work, I have to fudge it by creating a list of amounts amt, so that it matches the list length of employees. This can't be correct; it is certainly a very ugly solution.
I had hoped that I could do:
return list(map(change_salary, employees, amt))
Where employees is mapped to the employees argument and amt was mapped to the amt argument within change_salaries function.
Is what I am trying to do with map possible and, if so, what should the code be?
I have looked through the suggested posts before posting this question - I can't find a matching problem - perhaps because I am not using the correct terminology?
CodePudding user response:
You can use currying, like with partial
from functools
:
from functools import partial
def change_salaries(employees: list, amt: int) -> list:
return list(map(partial(change_salary, amt=amt), employees))