- Mastering Python
- Rick van Hattem
- 194字
- 2021-07-16 11:10:34
dict comprehensions
dict
comprehensions are very similar to list comprehensions, but the result is a dict
instead. Other than this, the only real difference is that you need to return both a key and a value, whereas a list
comprehension accepts any type of value. The following is a basic example:
>>> {x: x ** 2 for x in range(10)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} >>> {x: x ** 2 for x in range(10) if x % 2} {1: 1, 3: 9, 9: 81, 5: 25, 7: 49}
The funny thing is that you can mix these two, of course, for even more unreadable magic:
>>> {x ** 2: [y for y in range(x)] for x in range(5)} {0: [], 1: [0], 4: [0, 1], 16: [0, 1, 2, 3], 9: [0, 1, 2]}
Obviously, you need to be careful with these. They can be very useful if used correctly, but the output quickly becomes unreadable, even with proper whitespace.
推薦閱讀
- C程序設計簡明教程(第二版)
- Redis Applied Design Patterns
- Azure IoT Development Cookbook
- Python高級編程
- TypeScript圖形渲染實戰:基于WebGL的3D架構與實現
- PLC編程及應用實戰
- 基于Struts、Hibernate、Spring架構的Web應用開發
- Windows Phone 7.5:Building Location-aware Applications
- 詳解MATLAB圖形繪制技術
- Buildbox 2.x Game Development
- Webpack實戰:入門、進階與調優(第2版)
- 算法設計與分析:基于C++編程語言的描述
- ASP.NET 4.0 Web程序設計
- Android移動應用開發項目教程
- Python+Office:輕松實現Python辦公自動化