简体   繁体   中英

linq-like sum function in python

I started programming in python after a time I was programming in c#, and in c# I used quite often did things like the following:

list.sum(x => x * 2);

where list contains some kind of a number.
is there any thing like this in python? for example i want to do this:

>> arr = range(1,10)
>> linq_like_sum(lambda x :  x**2 , arr)

and get the sum of squares of arr.

Just use a generator expression:

lst = [1, 2, 3, 4, 5]
sum(x*x for x in lst)

> 55

尝试使用内置sum()的生成器表达式:

sum(x ** 2 for x in arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM