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

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.

主站蜘蛛池模板: 体育| 延边| 林口县| 东光县| 竹山县| 景洪市| 罗甸县| 霍邱县| 寻乌县| 霍邱县| 瓦房店市| 临朐县| 禹城市| 德兴市| 二连浩特市| 茂名市| 马山县| 浦江县| 军事| 贵南县| 雷波县| 宕昌县| 博白县| 乌海市| 平罗县| 南漳县| 抚松县| 安龙县| 武平县| 灵台县| 乡宁县| 桑植县| 平安县| 东乌珠穆沁旗| 高邑县| 卫辉市| 西乌珠穆沁旗| 丹凤县| 平遥县| 昆山市| 泸溪县|