- Functional Python Programming
- Steven F. Lott
- 163字
- 2021-08-27 19:20:28
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.
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- TypeScript Essentials
- 軟件項目管理(第2版)
- Vue.js 2 and Bootstrap 4 Web Development
- Java技術手冊(原書第7版)
- Apache Spark Graph Processing
- Visual Basic程序設計教程
- Visual C
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- Learning PHP 7
- C語言程序設計
- C++反匯編與逆向分析技術揭秘(第2版)
- R用戶Python學習指南:數據科學方法
- .NET 4.5 Parallel Extensions Cookbook
- C編程技巧:117個問題解決方案示例