[英]Reading lines from a file using a generator comprehension vs a list comprehension
以下代碼來自 Jake VanderPlas 的 Python 數據科學手冊的第 3 章。 文件中的每一行都是有效的 JSON。 雖然我認為文件的細節對於回答這個問題並不重要,但文件的 url 是https://github.com/fictivekin/openrecipes 。
# read the entire file into a Python array
with open('recipeitems-latest.json', 'r') as f:
# Extract each line
data = (line.strip() for line in f)
# Reformat so each line is the element of a list
data_json = "[{0}]".format(','.join(data))
# read the result as a JSON
recipes = pd.read_json(data_json)
兩個問題:
你在這里有兩個問題:
>>> f = open('things_which_i_should_know')
>>> data = (line.strip() for line in f)
>>> type(data)
<class 'generator'>
>>> data = [line.strip() for line in f]
>>> type(data)
<class 'list'>
>>>
請參閱官方文檔了解更多信息。
通過列表理解,您將返回 Python 列表; stripped_list 是包含結果行的列表,而不是迭代器。 生成器表達式返回一個迭代器,它根據需要計算值,而不需要一次實現所有值。 這意味着如果您正在使用返回無限 stream 或大量數據的迭代器,列表推導式就沒有用了。 在這些情況下,生成器表達式更可取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.