【问题标题】:Multiple Assignments in Python dictionary comprehensionPython字典理解中的多重赋值
【发布时间】:2013-07-24 14:26:29
【问题描述】:

假设我有一个列表

demo  = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']]

我想使用看起来像这样的理解来制作字典列表

[{'Adam':'Chicago', 'Gender':'Male', 'Location':'Chicago', 'Team':'Bears'},
{'Brandon':'Miami', 'Gender':'Male', 'Location':'Miami', 'Team':'Dolphins'} }

分配两个起始值很容易得到类似的东西

{ s[0]:s[1] for s in demo} 

但是有没有一种合法的方法可以在这个理解中分配多个值,可能看起来像

{ s[0]:s[1],'Gender':s[2], 'Team':s[3] for s in demo} 

这是一个具体的问题,我不知道搜索的术语,所以我很难找到它,上面的例子给了我一个语法错误。

【问题讨论】:

    标签: python dictionary python-3.x list-comprehension


    【解决方案1】:

    字典推导构建单个字典,而不是字典列表。你说你想制作一个字典列表,所以使用列表推导来做到这一点。

    modified_demo = [{s[0]:s[1],'Gender':s[2], 'Team':s[3]} for s in demo]
    

    【讨论】:

    • 序列分配会好很多。
    【解决方案2】:

    您可以使用 zip 将每个条目转换为键值对列表:

    dicts= [dict(zip(('Name','Gender','Location', 'Team'), data) for data in demo]
    

    您不想要“名称”标签,您想使用名称作为重复位置的标签。所以,现在你需要修复字典:

    for d in dicts:
        d[d['Name']] = d['Location']
        del d['Name'] # or not, if you can tolerate the extra key
    

    或者,您可以一步完成:

    dicts = [{name:location,'Location':location,'Gender':gender, 'Team':team} for name,location,gender,team in demo]
    

    【讨论】:

    • @JonClements 好吧,这与您的解决方案相同,只是多了一个步骤。
    【解决方案3】:

    您的要求看起来很奇怪,您确定您没有尝试对字段进行逻辑命名(这更有意义):

    >>> demo  = [['Adam', 'Chicago', 'Male', 'Bears'], ['Brandon', 'Miami', 'Male', 'Dolphins']]
    >>> [dict(zip(['name', 'location', 'gender', 'team'], el)) for el in demo]
    [{'gender': 'Male', 'team': 'Bears', 'name': 'Adam', 'location': 'Chicago'}, {'gender': 'Male', 'team': 'Dolphins', 'name': 'Brandon', 'location': 'Miami'}]
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 2014-02-08
      • 2019-04-15
      • 2023-03-04
      • 2014-05-06
      • 2013-03-24
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      相关资源
      最近更新 更多