使用生成器表达式取代列表解析可以同时节省CPU 和 内存(RAM)。如果你构造一个列表的目的仅仅是传递给别的函数,(比如 传递给tuple()
或者 set()
), 用生成器表达式替代吧!
for c in a_string:
yield ord(c)
gen = ord_map(unique_characters)
>>> unique_characters = {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'}
>>> gen = (ord(c) for c in unique_characters)
>>> gen
<generator object <genexpr> at 0x02EE1C38>
>>> next(gen)
69
>>> next(gen)
68
>>> tuple((ord(c) for c in unique_characters))
(69, 68, 77, 79, 78, 83, 82, 89)
>>> set((ord(c) for c in unique_characters))
{68, 69, 77, 78, 79, 82, 83, 89}
>>> list((ord(c) for c in unique_characters))
[69, 68, 77, 79, 78, 83, 82, 89]
>>>