Python 怎么将列表类字典组字符串转换为列表?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 怎么将列表类字典组字符串转换为列表?相关的知识,希望对你有一定的参考价值。
有如下一组字符串,
["id":100220748688221696701923815,"ts":1614576522050,"tradeId":7500734,"amount":1152.43,"price":0.01852,"direction":"sell"]
怎么将他转换成字典类列表,或者其他方法,我需要直接读取ID TS tradeID 项目
注意 最后一项direction 项目不像其他的没有冒号
字符串如下,因为字数限制,我附件了图片分别是EVAL 和JSON.LOADS的报错
["id":100569603575223726729043332,"ts":1614588720703,"tradeId":3853176,"amount":8.69,"price":19.6403,"direction":CCR]
我就说嘛,这个是为最后的CCR需要特殊处理的,要在字符串中加入引号才能用jsonloads
以前写过类似的,你看看
参考技术Alist1=["id":100220748688221696701923815,"ts":1614576522050,"tradeId":7500734,"amount":1152.43,"price":0.01852,"direction":"sell"]
list_new=[]
d=list1[0]
print(d)
for key in d:
list_new.append(key)
list_new.append(d[key])
print(list_new)
可能有一些没说清楚,字符串是通过
compressData = ws.recv()
result = gzip.decompress(compressData).decode('utf-8')
解析出来,通过查找截取字符后生成
["id":100220748688221696701923815,"ts":1614576522050,"tradeId":7500734,"amount":1152.43,"price":0.01852,"direction":"sell"] 列表样的字符串
我用了json.loads 和EVAL 但是都不能变成list,
不知理解得对不对,你看看:
test = [
['id':11,
'ts':12,
'tradeId':13,
'amount':14,
'price':15,
'direction':'1'
],
['id':21,
'ts':22,
'tradeId':23,
'amount':24,
'price':25,
'direction':'2'
],
['id':31,
'ts':32,
'tradeId':33,
'amount':34,
'price':35,
'direction':'3'
],
]
result = 'id':[],'ts':[],'tradeId':[],'amount':[],'price':[],'direction':[]
for row in test:
for sub_row in row:
result['id'].append(sub_row['id'])
result['ts'].append(sub_row['ts'])
result['tradeId'].append(sub_row['tradeId'])
result['amount'].append(sub_row['amount'])
result['price'].append(sub_row['price'])
result['direction'].append(sub_row['direction'])
由于太复杂的功能不会用列表推导式,所以就做成循环了,即最后是一个字典,字典中的值是列表:
Python字符串元组列表字典互相转换的方法
直接上代码!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
#-*-coding:utf-8-*- #1、字典 dict = { ‘name‘ : ‘Zara‘ , ‘age‘ : 7 , ‘class‘ : ‘First‘ } #字典转为字符串,返回:<type ‘str‘> {‘age‘: 7, ‘name‘: ‘Zara‘, ‘class‘: ‘First‘} print type ( str ( dict )), str ( dict ) #字典可以转为元组,返回:(‘age‘, ‘name‘, ‘class‘) print tuple ( dict ) #字典可以转为元组,返回:(7, ‘Zara‘, ‘First‘) print tuple ( dict .values()) #字典转为列表,返回:[‘age‘, ‘name‘, ‘class‘] print list ( dict ) #字典转为列表 print dict .values #2、元组 tup = ( 1 , 2 , 3 , 4 , 5 ) #元组转为字符串,返回:(1, 2, 3, 4, 5) print tup.__str__() #元组转为列表,返回:[1, 2, 3, 4, 5] print list (tup) #元组不可以转为字典 #3、列表 nums = [ 1 , 3 , 5 , 7 , 8 , 13 , 20 ]; #列表转为字符串,返回:[1, 3, 5, 7, 8, 13, 20] print str (nums) #列表转为元组,返回:(1, 3, 5, 7, 8, 13, 20) print tuple (nums) #列表不可以转为字典 #4、字符串 #字符串转为元组,返回:(1, 2, 3) print tuple ( eval ( "(1,2,3)" )) #字符串转为列表,返回:[1, 2, 3] print list ( eval ( "(1,2,3)" )) #字符串转为字典,返回:<type ‘dict‘> print type ( eval ( "{‘name‘:‘ljq‘, ‘age‘:24}" )) |
以上是关于Python 怎么将列表类字典组字符串转换为列表?的主要内容,如果未能解决你的问题,请参考以下文章