幂运算:**
》正负号:+x -x
》算术操作符: * / // + -
》比较操作符: < <= > >= == !=
》逻辑运算符: not and or
三元运算又称三目运算,是对简单的条件语句的简写
简单条件语句:
if 条件成立:
val = 1
else:
val = 2
改成三元运算:
val = 1 if 条件成立 else 2
>>> a =3
>>> b =7
>>> val = a if a<b else b
>>> val
3
assert 断言函数
函数定义:
assert 表达式 [, 参数]
当表达式为真时,程序继续往下执行,只是判断,不做任何处理;
当表达式为假时,抛出AssertionError错误,并将 [参数] 输出;
>>> a =3
>>> b =7
>>> assert a<b
>>> assert a>b
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
assert a>b
AssertionError
列表:一个打了激素的数组
a=[1,“htll”,(5,6)]
列表是Python中非常重要的数据类型,通常作为函数的返回类型。
列表中的元素的值可以改变,元素类型可以不同(可以是数字、字符、或者序列),元素可重复。
列表中的元素可以是元组或其他序列
列表可以相加和乘以一个整数,列表不支持相减、相除和除以一个数
>>> a =[1,2,3]
>>> b =[4,5,6]
>>> print(a+b)
[1, 2, 3, 4, 5, 6]
>>> print(a*3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
append(x)在列表末尾处加入一个元素x
>>> c =[1,1,2,'gjh','hhh']
>>> c.append(3)
>>> c
[1, 1, 2, 'gjh', 'hhh', 3]
count(x)返回元素x在列表中的个数
>>> c
[1, 1, 2, 'gjh', 'hhh', 3]
>>> c.count(1)
2
extend(x)将x的所有元素添加到列表末尾
>>> c
[1, 1, 2, 'gjh', 'hhh', 3]
>>> c.extend(['s','d','ggg'])
>>> c
[1, 1, 2, 'gjh', 'hhh', 3, 's', 'd', 'ggg']
index(x) 返回第一个元素x的索引
>>> c
[1, 1, 2, 'gjh', 'hhh', 3, 's', 'd', 'ggg']
>>> c.index('gjh')
3
insert(i,x) 将元素x插入都列表i位置
>>> c
[1, 1, 2, 'gjh', 'hhh', 3, 's', 'd', 'ggg']
>>> c.insert(2,'gjh')
>>> c
[1, 1, 'gjh', 2, 'gjh', 'hhh', 3, 's', 'd', 'ggg']
pop(i) 删除并返回索引为i的元素,无参时默认删除最后一个元素
>>> c
[1, 1, 'gjh', 2, 'gjh', 'hhh', 3, 's', 'd', 'ggg']
>>> c.pop()
'ggg'
>>> c.pop(2)
'gjh'
>>> c
[1, 1, 2, 'gjh', 'hhh', 3, 's', 'd']
remove(x) 删除列表中第一个元素x
>>> c
[1, 3, 1, 2, 'gjh', 'hhh', 3, 's', 'd']
>>> c.remove(3)
>>> c
[1, 1, 2, 'gjh', 'hhh', 3, 's', 'd']
>>> c.remove(3)
>>> c
[1, 1, 2, 'gjh', 'hhh', 's', 'd']
reverse()反转列表元素的排列顺序
>>> c
[1, 1, 2, 'gjh', 'hhh', 's', 'd']
>>> c.reverse()
>>> c
['d', 's', 'hhh', 'gjh', 2, 1, 1]
sort() 将列表按升序排列
>>> d = [2,3,4,6,1,2]
>>> d.sort()
>>> d
[1, 2, 2, 3, 4, 6]
降序
>>> d = [2,3,4,6,1,2]
>>> d.sort()
>>> d
[1, 2, 2, 3, 4, 6]
>>> d.reverse()
>>> d
[6, 4, 3, 2, 2, 1]
或
>>> d
[1, 2, 2, 3, 4, 6]
>>> d.sort(reverse=True)
>>> d
[6, 4, 3, 2, 2, 1]
列表生成式
根据已有列表,高效创建新列表的方式。列表生成式是Python迭代机制的一种应用,它常用于实现创建新的列表,因此用在[ ]中。
语法:[ expression for iter_val in iterable if cond_expr ]
>>> [i for i in range(10) if i<5 ]
[0, 1, 2, 3, 4]
列表去重
fromkeys()方法语法:{}.fromkeys(seq[, value]) 用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
字典函数values(),keys(),items(),三个函数都是查看字典中元素的函数,返回值都为一个list(列表)
用于去重列表中重复元素。
>>> c
['d', 'gjh', 'hhh', 's', 2, 1, 1]
>>> dict1 ={}
>>> c = list(dict1.fromkeys(c).keys())
>>> c
['d', 'gjh', 'hhh', 's', 2, 1]