1、通过列表推导式完成下面数据类型转换
现在有以下数据, li1 = ["{'a':11,'b':2}","[11,22,33,44]"]
需要转换为以下格式:li1 = [{'a':11,'b':2},[11,22,33,44]]
--------------答案在后面,先自己思考一下-----------------
2、 请通过列表推导式,获取names中字符串长度大于4的元素
Names=['python','java','php','c','c++','django','unittest','pytest','pymysql']
--------------答案在后面,先自己思考一下-----------------
3、通过字典推导式,颠倒字典的键名和值:
将
{'py': "python09", 'java': "java09"}
转换为:
{'python09': "py", 'java09': "java"}
--------------答案在后面,先自己思考一下-----------------
4、将字典 {'x': 'A', 'y': 'B', 'z': 'C' }
通过推导式转换为:['x=A','y=B','z=C']
--------------答案在后面,先自己思考一下-----------------
#coding=utf-8
# 1、通过列表推导式完成下面数据类型转换
# 现在有以下数据, li1 = ["{'a':11,'b':2}","[11,22,33,44]"]
# 需要转换为以下格式: li1 = [{'a':11,'b':2},[11,22,33,44]]
li1 = ["{'a':11,'b':2}","[11,22,33,44]"]
li2 = [eval(i) for i in li1]
print("第一题:li2={}".format(li2))
# 2、 Names=['python','java','php','c','c++','django','unittest','pytest','pymysql'],
# 请通过列表推导式,获取names中字符串长度大于4的元素
Names=['python','java','php','c','c++','django','unittest','pytest','pymysql']
LengthThanFour = [i for i in Names if len(i)>4]
print("第二题:LengthThanFour={}".format(LengthThanFour))
# 3、通过字典推导式,颠倒字典的键名和值:将{'py': "python09", 'java': "java09"}
# 转换为: {'python09': "py", 'java09': "java"}
dict1 = {'py': "python09", 'java': "java09"}
reverseDict = {value:key for key,value in dict1.items()}
print("第三题:reverseDict = {} ".format(reverseDict))
# 4、将字典{'x': 'A', 'y': 'B', 'z': 'C' }
# 通过推导式转换为:['x=A','y=B','z=C']
dict2 = {'x': 'A', 'y': 'B', 'z': 'C' }
dictToList = [key+'='+value for key,value in dict2.items()]
print("第四题dictToList = {}".format(dictToList))
#========================输出结果==============================#
第一题:li2=[{'a': 11, 'b': 2}, [11, 22, 33, 44]]
第二题:LengthThanFour=['python', 'django', 'unittest', 'pytest', 'pymysql']
第三题:reverseDict = {'python09': 'py', 'java09': 'java'}
第四题dictToList = ['x=A', 'y=B', 'z=C']