trouble using lambda in python
I am trying to write a lambda where it takes the minutes and divides it by a range, then prints out the result. I tried
list((lambda minutes: minutes / range),range(Numbe+1,1))
but list only takes one argument, any ideas? Minutes and Number the user supplies
I figured it out using
List=[]
List=range(1, Number+1)
开发者_JAVA技巧 List.reverse()
print(List)
for number in List:
print ( minutes/ number)
I know that the code look very novice and would appreciate any tips to get is to look better
Do you really need to use a lambda? Here is a list comprehension which most people seem to find easier to read
[float(minutes)/number for minutes in range(1,number+1)]
The equivalent using a lambda function is
map(lambda minutes: float(minutes)/number, range(1,number+1))
And a shorter way to write that is
map(float(number).__rdiv__, range(1,number+1))
The float
function is needed here (unless you are using Python3) because otherwise an integer division is done
What you are looking for is map
built-in function, which acts upon individual elements of the container passed to it as the second argument and returns the result which is a list. The first argument is many a times a lambda which takes the argument and acts upon it. In your case, the minutes and number.
map(lambda number:number/rangeval,range(1,rangeval))
精彩评论