[英]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.