【问题标题】:Getting a list of values from a list of dict in python: Without using list comprehension从python中的dict列表中获取值列表:不使用列表理解
【发布时间】:2013-07-20 08:11:21
【问题描述】:

例如,我有一个 dict 列表,

[{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]

现在,我必须在不使用列表理解的情况下从此字典中检索以下列表

[u'Library', u'Arts', u'Sports']

有没有办法在 python 中实现这一点?我看到很多类似的问题,但所有答案都使用列表理解。

感谢任何建议。提前致谢。

【问题讨论】:

  • 你为什么这么害怕列表推导?

标签: python


【解决方案1】:

你可以在这里使用map()map() 将 lambda 应用于 testList 的每个项目并将其作为列表返回。

>>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]
>>> map(lambda x: x['name'], testList)
[u'Library', u'Arts', u'Sports']

【讨论】:

    【解决方案2】:

    这里-

    ltemp = [] 
    for i in dictT:
        ltemp.append(i['name'])
    

    ltemp 是必需的列表。 dictT 是您的字典列表。

    【讨论】:

      【解决方案3】:

      您可以将map()lambda 一起使用:

      >>> dlist = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name':  u'Sports'}]
      
      >>> map(lambda d: d['name'], dlist)
      [u'Library', u'Arts', u'Sports']
      

      【讨论】:

        【解决方案4】:

        你可以使用itemgetter:

        from operator import itemgetter
        
        categories = map(itemgetter('name'), things)
        

        但是列表理解也很好。列表推导有什么问题?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-20
          • 2020-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-20
          相关资源
          最近更新 更多