4 ms·
I think this would be the Python equivalent: x = [1, 2, 3, 4] x = map(lambda x: x*x, x) x = filter(lambda x: x < 10, x) x = list(x) Or is ther
by TekMol 5y ago
I think this would be the Python equivalent:
x = [1, 2, 3, 4]
x = map(lambda x: x*x, x)
x = filter(lambda x: x < 10, x)
x = list(x)
Or is there a more elegant way?
- slightwinder 5y agoYou can write this as a oneliner too. But the problem here is not lambda, but the lack of map/filter-methods on list. Disputable whether this is good or bad.
- kangalioo 5y agoThis, maybe ```py x = [xx for x in [1, 2, 3, 4] if xx < 10] ```
- williamstein 5y agoI thought what you wrote wasn't valid because xx isn't defined in the scope of the inequality... however I now realize that's because Hacker News deletes the asterisks. In any case, it's [x [asterisk] x for x in [1,2,3,4] if x[asterisk] x < 10] which is still a little annoying because the x [asterisk] x gets computed twice. This is one of those little details that really annoys mathematicians, as I saw with SageMath for decades (I started SageMath -- which uses Python -- and got no end of complaints about the above). In the Magma programming language there is a "where" version of comprehensions that eloquently solves this problem as explained here: http://magma.maths.usyd.edu.au/magma/handbook/text/10 http://magma.maths.usyd.edu.au/magma/handbook/text/10 For example, { xx : x in [1 .. 4] | xx lt 10 where xx is x*x} which you can try at http://magma.maths.usyd.edu.au/calc/ http://magma.maths.usyd.edu.au/calc/
- dragonwriter 5y ago> however I now realize that’s because Hacker News deletes the asterisks You can escape asterisks with a backslash. \* => *
- deleted 5y ago[deleted]
- lvass 5y agofrom functools import partial from itertools import repeat from operator import pow,gt x = list(filter(partial(gt,10), map(pow, [1, 2, 3, 4], repeat(2)))) (please don't do this)