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

  • 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}

Note

Since the output is a dictionary, the key needs to be hashable for the dict comprehension to work.

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.

主站蜘蛛池模板: 洛川县| 始兴县| 宾阳县| 安宁市| 依安县| 香港 | 广南县| 镇远县| 隆德县| 和林格尔县| 扎兰屯市| 呼玛县| 金寨县| 襄樊市| 恭城| 肃宁县| 迁安市| 宁晋县| 图片| 元阳县| 平乡县| 会泽县| 东方市| 宜兰县| 革吉县| 香港 | 阿克苏市| 醴陵市| 吴堡县| 南华县| 建湖县| 磴口县| 陇西县| 海伦市| 龙江县| 日土县| 平原县| 永修县| 温州市| 黑山县| 黔西|