简体   繁体   English

python中类似linq的sum函数

[英]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: 在我用c#编程之后,我开始在python中编程,而在c#中,我经常使用类似下面的内容:

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

where list contains some kind of a number. list包含某种数字。
is there any thing like this in python? 在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. 得到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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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