这应该是一个简单的,但是因为我对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([data['type'] for data in alldata])
list_of_name = [data['name'] for data in alldata if data['type']==type]
关于python - 一键创建字典列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25568964/