Effective Python‘ Notebook
  • Introduction
  • 第 1 章 用Pythonic方式来思考
    • PE8风格指南
    • bytes,str和unicode
    • 用列表推导取代map和filter
Powered by GitBook
On this page

Was this helpful?

  1. 第 1 章 用Pythonic方式来思考

用列表推导取代map和filter

>>> a = list('123456789')
>>> a
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> [int(x)**2 for x in a]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
>>> rank_dict = {rank: name for name, rank in chile_ranks.items()}
>>> rank_dict
{1: 'ghost', 2: 'habanero', 3: 'cayenne'}
>>> {len(name) for name in rank_dict.values()}
{8, 5, 7}
Previousbytes,str和unicode

Last updated 6 years ago

Was this helpful?