1、推导式
推导式又叫做解析式,是简化冗余代码实质有效的方法,Python
中实用的语法糖,可以分为以下几类:
- 列表推导式(⭐)
- 字典推导式(⭐)
- 集合推导式
- 元祖推导式
下面只介绍常用的列表推导式和字典推导式。
1.1 列表推导式
对列表中每个元素进行一定操作。
基本使用
1 2 3 4
| list = [1,2,3,4,5,6,7,8,9,10] list1 = [x+2 for x in list] print(list1)
PYTHON
|
条件表达式
1 2 3 4
| list = ["Bob","Jason","Peter","Jani","Tom"] list1 = [name+"666" for name in list if len(name) > 3] print(list1)
PYTHON
|
多个 for 循环
1 2 3
| time = ['%.2d:%.2d'%(h,m )for h in range(24) for m in range(0,60,5) ] print(time)
PYTHON
|
多个 for 循环+条件表达式
1 2 3
| list = [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] print(list)
PYTHON
|
1.2 字典推导式
1 2 3 4
| listdemo = ["Bob","Jason","Peter","Jani","Tom"] newdict = {key:len(key) for key in listdemo} print(newdict)
PYTHON
|
互换 key 和 value 的值
1 2 3 4
| person = {'角色名':'宫本武藏','定位':'刺客'} person_reverse = {k:v for v,k in person.items()} print(person_reverse)
PYTHON
|
2、字典遍历
1 2 3
| person = {'角色名':'宫本武藏','定位':'刺客'} for key,value in person.items(): print(key,value)
PYTHON
|
3、判断元素是否在列表中
1 2 3 4
| listdemo = ["Bob","Jason","Peter","Jani","Tom"] if "Peter" in listdemo: print("Yes")
PYTHON
|
4、反转字符串
1 2 3 4
| name = "Tom" reverse_name = name[::-1] print(reverse_name)
PYTHON
|
5、反转列表
1 2 3 4
| name_list = ["Bob","Jason","Peter","Jani","Tom"] reverse_name_list = name_list[::-1] print(reverse_name_list)
PYTHON
|
6、获取时间
获取当前时间
1 2 3 4
| import datetime current_time = datetime.datetime.now() print(current_time)
PYTHON
|
获取当前日期
1 2 3 4
| import datetime current_date = datetime.date.today() print("当前日期:", current_date)
PYTHON
|
获取毫秒级时间(程序执行时间)
1 2 3 4 5 6 7
| import time start_time = time.time() numbers = [i for i in range(1000000)] end_time = time.time() time_ = end_time - start_time print(time_)
PYTHON
|
7、三元运算符
1 2 3 4 5
| a = 1 b = 2 max = a if a>b else b print(max)
PYTHON
|
8、枚举循环
1 2 3 4 5
| fruits = ['apple','banana'] for index,fruit in enumerate(fruits): print(index,fruit)
PYTHON
|