about 3 years ago

Consider Generator Expressions for Large Comprehensions

反正就是要注意 list comprehensions 可能造成 memory 爆掉。

使用 list comprehensions

import random

with open('/tmp/my_file.txt', 'w') as f:
    for _ in range(10):
        f.write('a' * random.randint(0, 100))
        f.write('\n')

value = [len(x) for x in open('/tmp/my_file.txt')]

使用 generator expressions

it = (len(x) for x in open('/tmp/my_file.txt'))
print(next(it))

相關

Python 慣用語 - 18 Generator Expressions

← Effective Python 心得筆記: Item 8 Effective Python 心得筆記: Item 10 →
 
comments powered by Disqus