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

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.

主站蜘蛛池模板: 唐海县| 昌都县| 满洲里市| 习水县| 河曲县| 石台县| 宁德市| 土默特右旗| 北票市| 华阴市| 化州市| 寻乌县| 文水县| 崇左市| 新干县| 鄂温| 雷山县| 南康市| 全州县| 姜堰市| 贵港市| 定日县| 青田县| 蓝山县| 千阳县| 乌兰察布市| 云浮市| 萨嘎县| 芒康县| 临漳县| 沂南县| 垫江县| 太保市| 罗平县| 宽甸| 特克斯县| 托克托县| 镇宁| 儋州市| 金门县| 龙泉市|