简体   繁体   English

python,生成器迭代一个或多个项目

[英]python, generator iterate with one or more items

I'm using pyyaml, and i'm loading a file.yml 我正在使用pyyaml,并且正在加载file.yml

stream = open("file.yml", "r")
results = yaml.load_all(stream)

results now contains a generator object. 结果现在包含一个生成器对象。

Then, i'm trying to process this: 然后,我正在尝试处理此问题:

for key, value in results:
    print(key, "->", value)

if i have more than one "yaml element" in my file.yml, this works fine. 如果我的file.yml中有多个“ yaml元素”,则可以正常工作。 example: 例:

foo: bar foo:栏

hello: world 你好,世界

but, if i have a only one "yaml element" in my file.yml, this is not working. 但是,如果我的file.yml中只有一个“ yaml元素”,则无法正常工作。 example: 例:

foo: bar foo:栏

the error is: ValueError: need more than 1 value to unpack 错误是: ValueError: need more than 1 value to unpack

i'm using python 3 我正在使用python 3

how can i solve this? 我该如何解决? the file.yml can contains 1 or more elements. file.yml可以包含1个或多个元素。

results is a list of dictionaries, so instead of iterating over that, you want to be iterating over the dictionaries: results是词典列表,因此,您不想遍历词典,而要遍历词典:

for dictionary in results:
    for key, value in dictionary.items():
        print(key, "->", value)

So you were trying to assign key to one dictionary, and value to another, because you were unpacking from the list and not the dictionary. 因此,您尝试将键分配给一个字典,将值分配给另一个,因为您是从列表而不是字典中解包。 dict.items() returns a list of tuples with the key in the first position and the value in the other of the tuple. dict.items()返回一个元组列表,键在第一个位置,值在另一个元组。

results = yaml.load_all(stream)
for doc in results:
    for k, v in doc.items():
        print(k, "->", v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM