- Functional Python Programming
- Steven F. Lott
- 175字
- 2021-08-27 19:20:29
Using enumerate() to include a sequence number
Python offers the enumerate() function to apply index information to values in a sequence or iterable. It performs a specialized kind of wrap that can be used as part of an unwrap(process(wrap(data))) design pattern.
It looks like the following code snippet:
>>> xi [1.47, 1.5, 1.52, 1.55, 1.57, 1.6, 1.63, 1.65, 1.68, 1.7, 1.73,
1.75, 1.78, 1.8, 1.83] >>> list(enumerate(xi)) [(0, 1.47), (1, 1.5), (2, 1.52), (3, 1.55), (4, 1.57),
(5, 1.6), (6, 1.63), (7, 1.65), (8, 1.68), (9, 1.7),
(10, 1.73), (11, 1.75), (12, 1.78), (13, 1.8), (14, 1.83)]
The enumerate() function transformed each input item into a pair with a sequence number and the original item. It's vaguely similar to the following:
zip(range(len(source)), source)
An important feature of enumerate() is that the result is an iterable and it works with any iterable input.
When looking at statistical processing, for example, the enumerate() function comes in handy to transform a single sequence of values into a more proper time series by prefixing each sample with a number.
推薦閱讀
- Learning Python Web Penetration Testing
- C語言程序設計實踐教程(第2版)
- JavaScript高效圖形編程
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- R語言數據可視化之美:專業圖表繪制指南
- concrete5 Cookbook
- Android程序設計基礎
- Nginx實戰:基于Lua語言的配置、開發與架構詳解
- Mastering Android Game Development
- Python機器學習之金融風險管理
- Modern C++ Programming Cookbook
- JavaScript+jQuery網頁特效設計任務驅動教程
- Distributed Computing in Java 9
- 從零開始學Selenium自動化測試:基于Python:視頻教學版
- Advanced Python Programming