# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/5/6 23:16 # @Author : "小多肉" # @Email : 1021181701@qq.com # @File : exdatatype.py # @Software: PyCharm """ todo: 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]"] # if 条件判断放在for循环后面 li1 = [eval(i) for i in li1 if isinstance(i,str)] # 第二种写法,if 条件判断放在for循环前面,此时必须加上else。 li2 = [eval(i) if isinstance(i,str) else i for i in li1 ] print(li1," ",li2) # todo: """ 2、使用列表推倒式生成一个[0,5,10,15,20,...50]的列表 """ li = [i for i in range(51) if i%5 == 0] print(li) # todo: """ 3、使用列表推到式生成一个[page1,page2,page3....page10]的列表 """ li = ["page{}".format(i) for i in range(1,11)] print(li) # todo: """ 4、 Names=['python','java','php','c','c++','django','unittest','pytest','pymysql'],请通过列表推导式,获取names中字符串长度大于4的元素 提示 :列表推导式可以结合三目运算符一起使用 """ Names=['python','java','php','c','c++','django','unittest','pytest','pymysql'] li4 = [i for i in Names if len(i)>4 ] print(li4) # todo: ''' 5、通过列表推导式和字典推导式完成下面数据转换 # 原来数据 str = """ url:www.baidu.com,mobilephone:13760246701,pwd:123456 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 """ # 转换后数据 list = [{'url': 'www.baidu.com', 'mobilephone': '13760246701', 'pwd': '123456'}, {'url': 'www.baidu.com', 'mobilephone': '15678934551', 'pwd': '234555'}, {'url': 'www.baidu.com', 'mobilephone': '15678934551', 'pwd': '234555'}, {'url': 'www.baidu.com', 'mobilephone': '15678934551', 'pwd': '234555'}, {'url': 'www.baidu.com', 'mobilephone': '15678934551', 'pwd': '234555'}] ''' string = """ url:www.baidu.com,mobilephone:13760246701,pwd:123456 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 url:www.baidu.com,mobilephone:15678934551,pwd:234555 """ exp_str = [{j.split(":")[0]:j.split(":")[1] for j in i.split(",") } for i in string.split(" ") if i] print(exp_str)