- 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.
推薦閱讀
- Developing Middleware in Java EE 8
- Julia機器學習核心編程:人人可用的高性能科學計算
- Java設計模式及實踐
- Oracle BAM 11gR1 Handbook
- Unity 5.x By Example
- 學習正則表達式
- Microsoft Azure Storage Essentials
- Java語言程序設計教程
- 小程序,巧應用:微信小程序開發實戰(第2版)
- Android Development Tools for Eclipse
- 軟件測試分析與實踐
- Functional Python Programming
- WCF全面解析
- 鋁合金陽極氧化與表面處理技術(第三版)
- Python從入門到項目實踐(超值版)