Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用字典列表的一个键创建列表_Python_List_Dictionary - Fatal编程技术网

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

Python 使用字典列表的一个键创建列表,python,list,dictionary,Python,List,Dictionary,这应该是一个简单的问题,但是因为我对python不太熟悉,所以我还没有完全弄清楚它是如何工作的。 我有以下csv文件 name ; type apple ; fruit pear ; fruit cucumber ; vegetable cherry ; fruit green beans ; vegetable 我想要实现的是列出所有不同的类型及其相应的名称,例如: fruit: apple, pear, cherry vegetabl

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

name        ; type
apple       ; fruit
pear        ; fruit
cucumber    ; vegetable
cherry      ; fruit
green beans ; vegetable
我想要实现的是列出所有不同的类型及其相应的名称,例如:

fruit: apple, pear, cherry
vegetable: cucumber, green beans
使用csv.DictReader读取它,我可以生成该csv文件的字典列表,保存在变量alldata中

alldata = 
[
  {'name':'apple', 'type':'fruit'},
  {'name':'pear',  'type':'fruit'},
  ...
]
现在我需要一个从alldata中列出所有不同类型值的列表

types = ??? #it should contain [fruit, vegetable]
这样我就可以遍历列表并提取与以下类型对应的姓名:

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
有人知道如何做到这一点吗?

使用以下结构:

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

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

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

list_of_name = [data['name'] for data in alldata if data['type']==type]

更通用的方法是使用itertools.groupby:

from itertools import groupby

food = [
    {'name': 'apple', 'type': 'fruit'}, 
    {'name': 'pear', 'type': 'fruit'}, 
    {'name': 'parrot', 'type': 'vegetable'}]

for group, items in groupby(sorted(food, key=lambda x: x['type']), lambda x: x['type']):
    print group, list(items) # here is group and items' objects in the group
结果是:

fruit [{'type': 'fruit', 'name': 'apple'}, {'type': 'fruit', 'name': 'pear'}]
vegetable [{'type': 'vegetable', 'name': 'parrot'}]
UPD:在分组之前对dict进行排序。感谢@mgilson的支持

生成一个迭代器,从iterable返回连续的键和组。键是为每个元素计算键值的函数。如果未指定或为“无”,则键默认为标识函数并返回未更改的元素通常情况下,iterable需要在同一个键函数上进行排序。


set(row[“type”]代表alldata中的row)
我接受了Gabz的答案,因为它还提供了关于如何构建姓名列表的信息。@kik没问题,这是你的电话:-)不管它值多少钱,除非食物按type.FWIW预先分类,
set(data['type']代表alldata中的数据)
在不创建中间列表的情况下执行相同的操作:-)