微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python将字典列表转换为元组列表

如何解决python将字典列表转换为元组列表

如何将字典列表转换为元组列表? 输入:

[{'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”对象不可下标

解决方法

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.values()。 values()也将按键(==输入)顺序:

data = [{'x': 0.4711900100474648,'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)]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。