python迭代目录列表

python迭代目录列表,python,list,iterator,Python,List,Iterator,我有一个我正在迭代的字典列表。我希望能够将列表传递给容器对象,然后在遍历容器时,通过检索每个dict的值的元组来遍历容器 例如: myDict = {"key1": "value1string", "key2": "value2string"} myList = [myDict] container = ContainerObj(myList) for value1, value2 in container: print "value1 = %s, value2 = %s" % val

我有一个我正在迭代的字典列表。我希望能够将列表传递给容器对象,然后在遍历容器时,通过检索每个dict的值的元组来遍历容器

例如:

myDict = {"key1": "value1string", "key2": "value2string"}
myList = [myDict]

container = ContainerObj(myList)
for value1, value2 in container:
    print "value1 = %s, value2 = %s" % value1, value2
我希望输出是:

"value1 = value1string, value2 = value2string"
如何在
ContainerObj
中定义
\uu iter\uuu
方法来实现这一点

我试着做了以下不起作用的事情:

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")
            )

要获得所需的输出,只需执行以下操作

t={'l':'t','t':'l'}

','.join('{}={}'.format(key, val) for key, val in t.items())

output = 'l=t,t=l'
我想你想要的是。通常在函数中使用
yield
而不是
return
来实现这一点。但在您的情况下,我认为您可以使用itertools来帮助:

from itertools import chain
item_gen = chain(d.values() for d in my_dicts_list)
# Edit: Note that this will give you values continuously (not what you want), should have done
# item_gen = (d.values() for d in my_dicts_list)
要对类执行此操作,可以执行以下操作:

class MyContainer(object):
    def __init__(self, my_list):
        self.the_list = my_list

    def __iter__(self):
        for d in self.the_list:
            yield d.values()
            # or:
            # yield (d.get("key1", None), d.get("key2", None))
然后您可以像使用任何iterable一样使用此对象:

my_con = MyContainer([{"a": 1, "b": 2}, {"a": 3, "b": 4}])
for val1, val2 in my_con:
    print "a = %s; b = %s" % (val1, val2)
编辑1:哎呀,意识到我在退货。你想要的只是价值观


而且,你基本上是自己制造发电机。使用内置的功能,它将更容易和更少的痛苦。我强烈建议查看
itertools
模块。还有字典的
iterkeys
itervalues
iteritems
方法。

已修复,尽管这是一个次要问题。你明白我的意思…我刚才也检查了:>>>dict={“a”:5}>>>mylist=[dict]>>>mylist[0]{'a':5}除非你是在评论,那是一个
列表
的一个
dict
,而不是多个,这是一个更次要的点。请不要覆盖内置名称(list,dict,等等)。稍后或现在,这会给您带来痛苦。我只是出于示例的目的使用了这些名称——它们不是我在代码中使用的变量名称。我知道还有其他方法可以迭代此列表。然而,我更感兴趣的是学习如何使用iter函数作为1。我是python的新手,对利用它的一些更强大的功能很感兴趣。二,。我发现另一种机制更干净。此外,您的示例已将
t
设置为
dict
。我正在尝试迭代一个
目录的
列表
。这正是我想要的!谢谢@daveydave400。