[英]Make list out of list comprehension using generator
我一直在嘗試將列表理解的輸出轉換為變量。 很愚蠢,但無論我嘗試什么,我似乎最終都會得到一個空列表(或 NoneType 變量)。
我猜它與它使用的生成器有關,但我不確定如何解決它,因為我需要生成器從我的 JSON 文件中檢索所需的結果。 (而且我對列表理解和生成器新手太多了,無法了解如何)。
我希望將print()
部分的輸出寫入列表。
def item_generator(json_Response_GT, identifier):
if isinstance(json_Response_GT, dict):
for k, v in json_Response_GT.items():
if k == identifier:
yield v
else:
yield from item_generator(v, identifier)
elif isinstance(json_Response_GT, list):
for item in json_Response_GT:
yield from item_generator(item, identifier)
res = item_generator(json_Response_GT, "identifier")
print([x for x in res])
任何幫助將不勝感激!
生成器保持其狀態,因此在您迭代一次(為了打印)之后,另一次迭代將在最后開始並且不產生任何結果。
print([x for x in res]) # res is used up here
a = [x for x in res] # nothing left in res
相反,請執行以下操作:
a = [x for x in res] # or a = list(res)
# now res is used up, but a is a fixed list - it can be read and accessed as many times as you want without changing its state
print(a)
res = [x for x in item_generator(json_Response_GT, "identifier")]
應該可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.