使用生成器从列表理解中创建列表
Make list out of list comprehension using generator
我一直在尝试将列表推导式的输出转换为变量。非常愚蠢,但无论我尝试什么,我似乎都得到一个空列表(或 NoneType 变量)。
我猜它与它使用的生成器有关,但我不确定如何解决它,因为我需要生成器从我的 JSON 文件中检索所需的结果. (而且我是一个列表理解和生成器新手,不知道如何操作)。
这是工作代码(最初发布是为了回答这些问题 (here and ))。
我想将 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])
如有任何帮助,我们将不胜感激!
res = [x for x in item_generator(json_Response_GT, "identifier")]
应该可以解决问题。
生成器保持其状态,因此在您迭代一次(为了打印)之后,另一次迭代将在最后开始并且不会产生任何结果。
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)
我一直在尝试将列表推导式的输出转换为变量。非常愚蠢,但无论我尝试什么,我似乎都得到一个空列表(或 NoneType 变量)。
我猜它与它使用的生成器有关,但我不确定如何解决它,因为我需要生成器从我的 JSON 文件中检索所需的结果. (而且我是一个列表理解和生成器新手,不知道如何操作)。
这是工作代码(最初发布是为了回答这些问题 (here and
我想将 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])
如有任何帮助,我们将不胜感激!
res = [x for x in item_generator(json_Response_GT, "identifier")]
应该可以解决问题。
生成器保持其状态,因此在您迭代一次(为了打印)之后,另一次迭代将在最后开始并且不会产生任何结果。
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)