我有一个字典列表,我正在反复阅读。我希望能够将列表传递给一个容器对象,然后在遍历容器时检索每个dict值的元组。在
例如:
myDict = {"key1": "value1string", "key2": "value2string"}
myList = [myDict]
container = ContainerObj(myList)
for value1, value2 in container:
print "value1 = %s, value2 = %s" % value1, value2
我希望输出是:
^{pr2}$我如何在ContainerObj
中定义__iter__
方法来实现这一点?在
我试着做了以下没用的事:
class ContainerObj(object):
def __init__(self, listArg):
self.myList = listArg
self.current = 0
self.high = len(self.myList)
def __iter__(self):
return self.myList.__iter__()
def __next__(self):
if self.current >= self.high:
raise StopIteration
else:
myDict = self.myList[self.current]
self.current += 1
return (
myDict.get("key1"),
myDict.get("key2")
)
要获得所需的输出,只需执行以下操作。在
我想你想要的是generators。通常通过在函数中使用
yield
而不是return
来实现这一点。但在您的情况下,我认为您可以使用itertools来帮助:要在类中执行此操作,可以执行以下操作:
^{pr2}$然后可以像使用任何iterable一样使用此对象:
编辑1:哎哟,我意识到我在退货。你只想要价值观。在
而且,你基本上是自己制造发电机。使用内置的功能,它将更容易和更少的痛苦。我强烈建议您看看}方法。在
itertools
模块。还有字典的iterkeys
、itervalues
、和{相关问题 更多 >
编程相关推荐