官术网_书友最值得收藏!

Using len() and sum()

The len() and sum() functions provide two simple reductions—a count of the elements and the sum of the elements in a sequence. These two functions are mathematically similar, but their Python implementation is quite different.

Mathematically, we can observe this cool parallelism. The len() function returns the sum of ones for each value in a collection, .

The sum() function returns the sum of x for each value in a collection, .

The sum() function works for any iterable. The len() function doesn't apply to iterables; it only applies to sequences. This little asymmetry in the implementation of these functions is a little awkward around the edges of statistical algorithms.

For empty sequences, both of these functions return a proper additive identity element of zero:

>>> sum(())
0

Of course, sum(()) returns an integer zero. When other numeric types are used, the integer zero will be coerced to the proper type for the available data.

主站蜘蛛池模板: 闻喜县| 青浦区| 石泉县| 祁连县| 天台县| 青海省| 六枝特区| 宝山区| 北流市| 满洲里市| 青川县| 东辽县| 南丰县| 昭通市| 朝阳市| 苍山县| 荣昌县| 伊宁市| 红河县| 五原县| 古丈县| 固始县| 左云县| 平罗县| 大同市| 马公市| 库尔勒市| 工布江达县| 阳山县| 新乐市| 嘉义县| 错那县| 泸水县| 大港区| 徐汇区| 克拉玛依市| 格尔木市| 永丰县| 历史| 神农架林区| 井冈山市|