使用字典列表的一键创建列表

kik*_*iki 4 python dictionary list

这应该是一个简单的问题,但是由于我对python不太熟悉,所以我还没有完全弄清楚它是如何工作的。我有以下 csv 文件

name        ; type
apple       ; fruit
pear        ; fruit
cucumber    ; vegetable
cherry      ; fruit
green beans ; vegetable
Run Code Online (Sandbox Code Playgroud)

我想要实现的是列出所有不同的类型及其相应的名称,例如:

fruit: apple, pear, cherry
vegetable: cucumber, green beans
Run Code Online (Sandbox Code Playgroud)

使用 csv.DictReader 读取它,我可以生成该 csv 文件的字典列表,保存在变量 alldata 中。

alldata = 
[
  {'name':'apple', 'type':'fruit'},
  {'name':'pear',  'type':'fruit'},
  ...
]
Run Code Online (Sandbox Code Playgroud)

现在我需要来自 alldata 的所有不同类型值的列表

types = ??? #it should contain [fruit, vegetable]
Run Code Online (Sandbox Code Playgroud)

这样我就可以迭代列表并提取与这些类型相对应的我的名字:

foreach type in types
  list_of_names = ??? #extract all values of alldata["type"]==type and put them in a new list
  print type + ': ' + list_of_names
Run Code Online (Sandbox Code Playgroud)

有谁知道如何实现这一目标?

小智 5

您可以使用列表理解来解决这个问题:

types = set([data['type'] for data in  alldata])

list_of_name = [data['name'] for data in alldata if data['type']==type]
Run Code Online (Sandbox Code Playgroud)

  • FWIW,`set(data['type'] for data in alldata)` 做同样的事情而不创建中间列表:-) (2认同)