ale*_*wis 2 python dictionary iterator class
我有一个超级简单的课程:
class Person():
def __init__(self, attributes_to_values):
self.attributes_to_values = attributes_to_values
Run Code Online (Sandbox Code Playgroud)
我使用如下:
attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)
Run Code Online (Sandbox Code Playgroud)
我想进行迭代,alex
以便返回attributes_to_values
属性中的键和相应的值。
我尝试插入以下内容:
def __iter__(self):
yield list(self.attributes_to_values.items())
Run Code Online (Sandbox Code Playgroud)
但这不起作用...
for a, v in alex:
print(a, v)
Run Code Online (Sandbox Code Playgroud)
回溯(最近一次调用):ValueError 中的文件“”,第 1 行:太多值无法解压(预期为 2)
如果你有一个像你这样的可迭代对象,item()
你可以yield from
:
class Person():
def __init__(self, attributes_to_values):
self.attributes_to_values = attributes_to_values
def __iter__(self):
yield from self.attributes_to_values.items()
attributes_to_values = dict(name='Alex', age=30, happiness=100)
alex = Person(attributes_to_values=attributes_to_values)
for a, v in alex:
print(a, v)
Run Code Online (Sandbox Code Playgroud)
印刷
name Alex
age 30
happiness 100
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1433 次 |
最近记录: |