一、问题的提出
微信群中有人问,如何把以下内容转换成一个列表:
转换后:
"[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]"
转换后:
["007674","工银产业升级股票A","GYCYSJGPA","1.3574","007675","工银产业升级股票C","GYCYSJGPC","1.3205","001719","工银国家战略股票","GYGJZLGP","2.25"]
二、问题分析
实现上述转换,需要第一步是把字符串转换为列表,我们可以用eval()函数就可以了。然后我还要对嵌套列表进行遍历,对于一个一子列表进行解包,可以通过列表推导式,也可以通过星号或者用列表相加,或者集合合并等多种方法。
以上嵌套列表是标准的列表,如果不是标准的列表,我们还需要用isinstance()来判断是不是一个列表,如果是的话再展开操作,这里可能用到了递归的方法。
1. 列表推导式法
首先,这是一个嵌套列表,如果外面有双引号则是字符串,可以通过eval()来去除,再用列表推导式解决。
data = '[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]'
s=[]
print([item for ls in eval(data) for item in ls])
代码运行展示:
2. for 循环法
data = '[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]'
s=[]
for lst in eval(data):
for ls in lst:
s.append(ls)
print(s)
代码运行展示:
3. 可以用星号解包并输出
用一个星号来解包列表,代码如下。但是最终只是输出,并没有生成列表,不符号题目的要求。
data = '[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]'
s=[]
for lst in eval(data):
print([*lst],sep=",",end="") 第一种方法
代码运行展示:
4. 列表相加法
简单的说就是把字符串转化为列表后,通过循环让里的元素相加。
lst = '[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]'
s=[]
for i in eval(lst):
s+=i
print(s)
5. 集合求并集
把列表转为集合,利用求并集的方法来求合并合的集合,最后通过list转换为列表。
lst = '[["007674","工银产业升级股票A","GYCYSJGPA","1.3574"],["007675","工银产业升级股票C","GYCYSJGPC","1.3205"],["001719","工银国家战略股票","GYGJZLGP","2.25"]]'
s=set()
for i in lst:
s= s|set(i)
print(list(s))
代码运行后的效果
三、注意事项
- 三种方法殊途同归,请有选择地使用。个人更喜欢列表表达式法,比较简洁,运行效率高。
- Python中我们可以用一个星号解包列表。但是星号解包不能用于列表推导式,所以说还是有点儿遗憾。