繁体   English   中英

如何将dict列表转换为两个列表?

[英]How to convert list of dict into two lists?

例如:

persons = [{'id': 1, 'name': 'john'}, {'id': 2, 'name': 'mary'}, {'id': 3, 'name': 'tom'}]

我想从中得到两个列表:

ids = [1, 2, 3]
names = ['john', 'mary', 'tom']

我做了什么:

names = [d['name'] for d in persons]
ids = [d['id'] for d in persons]

有更好的方法吗?

你所做的工作正常。 处理这个问题的另一种方法(不一定更好,取决于您的需要)是将您的数据存储在更有效的字典中,并在需要时从中提取名称/ID:

>>> persons = [{'id': 1, 'name': 'john'}, {'id': 2, 'name': 'mary'}, {'id': 3, 'name': 'tom'}]
>>> p2 = {x['id']: x['name'] for x in persons}
>>> p2
{1: 'john', 2: 'mary', 3: 'tom'}

>>> list(p2.keys())
[1, 2, 3]

>>> list(p2.values())
['john', 'mary', 'tom']

您可以使用 pandas 以矢量化方式执行此操作:

import pandas as pd
persons = [{'id': 1, 'name': 'john'}, {'id': 2, 'name': 'mary'}, {'id': 3, 'name': 'tom'}]

df = pd.DataFrame(persons)
id_list = df.id.tolist() #[1, 2, 3]
name_list = df.name.tolist() #['john', 'mary', 'tom']

我会坚持使用列表理解或使用@Woodford 技术

ids,name = [dcts['id'] for dcts in persons],[dcts['name'] for dcts in persons]

output

[1, 2, 3] 
['john', 'mary', 'tom']

听起来您在解压缩字典时尝试遍历列表的值:

persons = [{'id': 1, 'name': 'john'}, {'id': 2, 'name': 'mary'}, {'id': 3, 'name': 'tom'}]


for x in persons:
    id, name = x.values()
    ids.append(id)
    names.append(name)

这个问题启发的另一种选择是

ids, names = zip(*map(lambda x: tuple(x.values()), persons))

在我的笔记本电脑上使用python3.9比接受的答案慢一点,但它可能有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM