【问题标题】:How to get unique values in Python using list/dict comprehension如何使用列表/字典理解在 Python 中获取唯一值
【发布时间】:2019-09-13 12:18:20
【问题描述】:

我只需要从字典中的“城市”字段中获取唯一值。我需要使用列表/字典理解来做到这一点。

people = [ dict ( city = "Liverpool" , name = "Adam" , age = 24 ),
{ "city" : "New York" , "name" : "Dario" , "age" : 12 },
{ "city" : "New York" , "name" : "Mario" , "age" : 45 },
{ "city" : "Chicago" , "name" : "Paolo" , "age" : 27 },
{ "city" : "Brighton" , "name" : "Sven" , "age" : 19 },
{ "city" : "Berlin" , "name" : "Frank" , "age" : 52 },
{ "city" : "Rome" , "name" : "Aleksander" , "age" : 33 }
{ "city" : "Rome" , "name" : "Adam," , "age" : 24 }]

我是这样用循环完成的:

unique_cities = []
for x in range(len(people)):
    y = people[x]
    cities = y.get('city')
    unique_cities.append(cities)
unique_cities = list(dict.fromkeys(unique_cities))
print(unique_cities)

但我之前没有处理过列表/字典理解。我只能像这样打印所有值:

for x in range(len(people)):
    y = people[x]
    dict_comp = {k:v for (k, v) in y.items()}
    print(dict_comp)

【问题讨论】:

  • print( list(set(i["city"] for i in people)) )

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


【解决方案1】:

列表推导,并将其传递给集合。

set(person['city'] for person in people)

注意:实际上,这是一个生成器表达式,不是列表推导式,但在这种情况下,它们在大多数情况下是等价的

【讨论】:

  • 既然可以直接做集合推导,为什么还要进行列表推导,然后再转换成集合?
  • @glhr:正确。其实我写的不是列表推导式。
【解决方案2】:

集合中的条目根据定义是唯一的,因此集合理解正是您在这里所需要的:

{d["city"] for d in people}

输出:

{'Berlin', 'Rome', 'Brighton', 'Liverpool', 'Chicago', 'New York'}

【讨论】:

    【解决方案3】:

    首先,请注意您的列表包含字典定义的两种语法:dict + keywordskey: value 在 accolades 中。这不是问题,但这很奇怪。

    其次,在 Python 中你通常不需要循环的索引:

    for x in range(len(people)):
        y = people[x]
        ...
    

    等同于:

    for y in people:
        ...
    

    如果你需要索引,你有enumerate关键字:

    for x, y in enumerate(people):
        ...
    

    第三:

        dict_comp = {k:v for (k, v) in y.items()}
    

    制作y 的(浅)副本并将其分配给dict_comp。在您的情况下,这不是必需的:

    for y in people:
        print(y)
    

    第四,dict.fromkeys 是穷人的set。两种解决方案大致相同,但 set 丢失了插入顺序(在 3.6 中测试),而 dict.fromkeys 保留了键的插入顺序(>= 3.6):

    >>> set(person['city'] for person in people)
    {'Rome', 'Chicago', 'New York', 'Brighton', 'Liverpool', 'Berlin'}
    >>> dict.fromkeys(person['city'] for person in people)
    {'Liverpool': None, 'New York': None, 'Chicago': None, 'Brighton': None, 'Berlin': None, 'Rome': None}
    

    如果你想要一个键第一次出现的顺序,你也可以这样写:

    >>> seen = set()
    >>> [person['city'] for person in people if not (person['city'] in seen or seen.add(person['city']))]
    ['Liverpool', 'New York', 'Chicago', 'Brighton', 'Berlin', 'Rome']
    

    每次遇到新的city 时,列表推导将其添加到输出和seen set(注意:列表推导中的副作用):

    >>> seen
    {'Berlin', 'Liverpool', 'Rome', 'New York', 'Brighton', 'Chicago'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 2017-07-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多