如何迭代这个列表?

2024-05-16 19:18:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我只有一份清单如下:

list =  [ [{u'name': u'Peter'} , {u'name': u'Kevin'} , {u'name': u'Earl'}] ]

我需要分别获取Peter Kevin Earl,并将其作为查询的参数。如何编写for循环?在

我想我的单子里有一个单子,里面有三本字典。我需要取每本字典的值。在


Tags: namefor参数字典listpeter单子kevin
3条回答
lst = [[{u'name': u'Peter'}, {u'name': u'Kevin'}, {u'name': u'Earl'}]] # Note that this is a list containing another list, containing dictionaries.
names = [x["name"] for x in lst[0]]

我不得不改变你原来的名单,因为“厄尔”被列为一个数字。:)

这就可以做到:

inner_values = [dictionary.values()[0] for dictionary in list[0]]

这个解决方案可以让你从内部映射中获得价值,不管关键是什么。在

first_list = [[{u'name': u'Peter'},{u'name': u'Kevin'},{u'name': u'Earl'}]]

names = []

# You loop over the whole list
for element in first_list:

    # For each element, you loop over the elements inside it
    for object in element:

        # Now, object is each one of the dictionaries 
        names.append(object["name"])

上面的代码应该可以工作,这里有一个更像Python的答案

^{pr2}$

在第一个列表中有多少个列表并不重要,因为您正在循环它。如果只有一个列表,循环将迭代一次。在

相关问题 更多 >