List, Set, and Dict Comprehensio

2018-12-03  本文已影响8人  闫_锋

List Comprehensions

In [154]: strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
In [155]: [x.upper() for x in strings if len(x) > 2]
Out[155]: ['BAT', 'CAR', 'DOVE', 'PYTHON']

Set Comprehensions

In [156]: unique_lengths = {len(x) for x in strings}
In [157]: unique_lengths
Out[157]: {1, 2, 3, 4, 6}

Dict Comprehension

In [158]: set(map(len, strings))
Out[158]: {1, 2, 3, 4, 6}

In [159]: loc_mapping = {val : index for index, val in enumerate(strings)}
In [160]: loc_mapping
Out[160]: {'a': 0, 'as': 1, 'bat': 2, 'car': 3, 'dove': 4, 'python': 5}
上一篇 下一篇

猜你喜欢

热点阅读