functional programming - Useful code which uses reduce() in python - Stack Overflow
The other uses I’ve found for it besides and * were with and and or, but now we have
anyandallto replace those cases.
foldlandfoldrdo come up in Scheme a lot…Here’s some cute usages:
Flatten a list
Goal: turn
[[1, 2, 3], [4, 5], [6, 7, 8]]into[1, 2, 3, 4, 5, 6, 7, 8].reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])List of digits to a number
Goal: turn
[1, 2, 3, 4, 5, 6, 7, 8]into12345678.Ugly, slow way:
int("".join(map(str, [1,2,3,4,5,6,7,8])))Pretty
reduceway:reduce(lambda a,d: 10*a d, [1,2,3,4,5,6,7,8], 0)
Posted via email from 思發隨醒 | Comment »