Trying to use reduce () and lambda with a list containing strings

I am trying to use the pythons abbreviation function in a list containing strings of integers.

print int("4") \\Gives me 4 Good print reduce(lambda x, y: x*y, [2, 3, 4]) \\Gives me 24 Good print reduce(lambda x, y: x*int(y), ['2', '3', '4']) \\Gives me 222222222222 What?? 

I assume the abbreviation gives lambda functions something that is not the actual line in the list? I have no idea why I am getting 222222222222 at least will there be an easy way to make an int list? I think I could just create another loop, but I still would like to know what happened with the line feed.

+4
source share
4 answers
 >>> reduce(lambda x, y: x*int(y), ['2', '3', '4']) '222222222222' 

Ok, here's what happens:

At the first reduction stage, the following calculation is performed: '2' * 3 . Since the first operand is a string, it just repeats 3 times. That way you get '222' .

In the second reduction step, this value is multiplied by 4: '222' * 4 . Again, the line is repeated four times, resulting in '222222222222' , which is exactly the result you got.

You could avoid this by converting x to int also (calling int(x) ) or by matching list items using integer conversion in the first place (I actually think this is more elegant):

 >>> reduce(lambda x, y: x * y, map(int, ['2', '3', '4'])) 24 
+7
source

You can try the following:

 reduce(lambda x, y: x*int(y), ['2', '3', '4'], 1) 

Notice that I pass the third parameter to reduce , indicating that the operation should be initialized to 1 , a multiplicative identity. Thus, you only need to convert y , the current value to int , and not x , the accumulated value.

+4
source

You multiply the string '2' by int 3, which gives the string '222' ... then the string '222' by int 4, which gives the string '222222222222'.

You need to convert x to an integer:

 print reduce(lambda x, y: int(x)*int(y), ['2', '3', '4']) 
+1
source
 multiply = lambda a,b: a*b listOfInts = map(int, ['2','3','4']) reduce(multiply, listOfInts) #output: 24 
0
source

Source: https://habr.com/ru/post/1401501/


All Articles