gpt4 book ai didi

python 2.7 : making a dictionary object from a specially-formatted list object

转载 作者:太空狗 更新时间:2023-10-30 01:58:43 25 4
gpt4 key购买 nike

我有一个列表类型的对象,如:

     f = [77.0, 'USD', 77.95, 
103.9549, 'EUR', 107.3634,
128.1884, 'GBP', 132.3915,
0.7477, 'JPY', 0.777]

我想创建一个如下的字典:

d = 
{'EUR': [103.9549, 107.3634],
'GBP': [128.1884, 132.3915],
'JPY': [0.7477, 0.777],
'USD': [77.0, 77.95]}

我尝试利用这些答案 Convert a list to a dictionary in Python , 和 Make dictionary from list with python .

但是,找不到正确的方法。

到目前为止,我的解决方案是:

cs = [str(x) for x in f if type(x) in [str, unicode]]
vs = [float(x) for x in f if type(x) in [int, float]]
d = dict(zip(cs, [[vs[i],vs[i+1]] for i in range(0,len(vs),2)]))

但是,什么才是聪明的单行代码?

最佳答案

怎么样:

In [5]: {f[i+1]: [f[i], f[i+2]] for i in range(0, len(f), 3)}
Out[5]:
{'EUR': [103.9549, 107.3634],
'GBP': [128.1884, 132.3915],
'JPY': [0.7477, 0.777],
'USD': [77.0, 77.95]}

关于 python 2.7 : making a dictionary object from a specially-formatted list object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23914774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com