簡體   English   中英

python將dict列表轉換為元組列表

[英]python convert list of dict to list of tuple

如何將 dict 列表轉換為元組列表? 輸入:

[{'x': 0.4711900100474648, 'y': 0.6294374442355883}, {'x': 0.4732473419066774, 'y': 0.629306809190704}, {'x': 0.47373722332499346, 'y': 0.6274779185623242}, {'x': 0.47363924704133026, 'y': 0.6273908285324014}, {'x': 0.4731493656230142, 'y': 0.6261715681134813}, {'x': 0.4722349203088243, 'y': 0.6252571227992915}, {'x': 0.47210428526394, 'y': 0.62521357778433}, {'x': 0.4709285698599815, 'y': 0.6253442128292143}, {'x': 0.47024273587433907, 'y': 0.62612802309852}, {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

我要這個:

[(0,47..., 0.62...),(...,...)]

我試過這個:

tupleList = [tuple(val['x'], val['y']) for dic in listOfDict for key,val in dic.items()]

我收到錯誤 TypeError: 'float' object is not subscriptable

list_of_points = [{'x': 0.4711900100474648, 'y': 0.6294374442355883}, {'x': 0.4732473419066774, 'y': 0.629306809190704}, {'x': 0.47373722332499346, 'y': 0.6274779185623242}, {'x': 0.47363924704133026, 'y': 0.6273908285324014}, {'x': 0.4731493656230142, 'y': 0.6261715681134813}, {'x': 0.4722349203088243, 'y': 0.6252571227992915}, {'x': 0.47210428526394, 'y': 0.62521357778433}, {'x': 0.4709285698599815, 'y': 0.6253442128292143}, {'x': 0.47024273587433907, 'y': 0.62612802309852}, {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

points_tuples = [(p['x'], p['y']) for p in list_of_points] 

如果您使用的是 python 3.7+ 並按 x,y 順序插入鍵(就像這里完成的那樣),您可以簡單地使用每個內部 dict 的dict.values() values() 也將按鍵 (==input) 順序排列:

data = [{'x': 0.4711900100474648, 'y': 0.6294374442355883}, 
        {'x': 0.4732473419066774, 'y': 0.629306809190704}, 
        {'x': 0.47373722332499346, 'y': 0.6274779185623242}, 
        {'x': 0.47363924704133026, 'y': 0.6273908285324014}, 
        {'x': 0.4731493656230142, 'y': 0.6261715681134813}, 
        {'x': 0.4722349203088243, 'y': 0.6252571227992915}, 
        {'x': 0.47210428526394, 'y': 0.62521357778433}, 
        {'x': 0.4709285698599815, 'y': 0.6253442128292143}, 
        {'x': 0.47024273587433907, 'y': 0.62612802309852}, 
        {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

tup = [tuple(d.values()) for d in data]

輸出:

[(0.4711900100474648, 0.6294374442355883), (0.4732473419066774, 0.629306809190704), 
 (0.47373722332499346, 0.6274779185623242), (0.47363924704133026, 0.6273908285324014), 
 (0.4731493656230142, 0.6261715681134813), (0.4722349203088243, 0.6252571227992915), 
 (0.47210428526394, 0.62521357778433), (0.4709285698599815, 0.6253442128292143), 
 (0.47024273587433907, 0.62612802309852), (0.4706019822477708, 0.6283052738465912)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM