n =10
result =1< n <20print(result)>>>True
result =11> n <20print(result)>>>True
使用三元操作符进行条件赋值
#三元操作符是 if-else 语句(也就是条件操作符)的快捷操作#[on_true] if [expression] else [on_false]
x =10if(y ==9)else20#同样,我们对类对象也可以这样操作:
x =(classA if y ==1else classB)(param1, param2)
将一个列表的元素保存到新变量中
testList =[1,2,3]
x, y, z = testList
print(x, y, z)>>>123
testDict ={i: i * i for i inrange(10)}
testSet ={i *2for i inrange(10)}print(testDict)print(testSet)>>>{0:0,1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64,9:81}>>>{0,2,4,6,8,10,12,14,16,18}
#我们可以通过调用 dir() 方法在 Python 中检查对象
test =[1,3,5,7]print(dir(test))>>>['__add__','__class__','__contains__','__delattr__','__delitem__','__delslice__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getslice__','__gt__','__hash__','__iadd__','__imul__','__init__','__iter__','__le__','__len__','__lt__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__reversed__','__rmul__','__setattr__','__setitem__','__setslice__','__sizeof__','__str__','__subclasshook__','append','count','extend','index','insert','pop','remove','reverse','sort']
简化if语句
#验证多个值if m in[1,3,5,7]:#也可以用字符串if m in'{1,3,5,7}'
在运行时检测Python的版本
import sys
ifnot sys.version_info >=(3,5):print("Sorry, you aren't running on Python 3.5 or late\n")print("Please upgrade to 3.5 or late.\n")
sys.exit(1)
组合多个字符串
test =['I','Like','Python','automation']print(" ".join(test))
翻转字符串/列表的4种方式
testList =[1,3,5]
testList.reverse()print(testList)>>>[5,3,1]#在循环中迭代时翻转for element inreversed([1,3,5]):print(element)>>>5>>>3>>>1#用切片翻转一个列表"Test Python"[::-1]>>>'nohtyP tseT'[1,3,5][::-1]>>>[5,3,1]
使用枚举
#使用枚举可以很容易地在循环中找到索引
testlist =[10,20,30]for i, value inenumerate(testlist):print(i,':', value)>>>0:10>>>1:20>>>2:30#在 Python3 中使用枚举量#我们可以用如下方法来创建枚举定义classShapes:
Circle, Square, Triangle, Quadrangle =range(4)print(Shapes.Circle)>>>0print(Shapes.Square)>>>1print(Shapes.Triangle)>>>2print(Shapes.Quadrangle)>>>3
从函数中返回多个值
返回多个值的函数
defx():return1,2,3,4
a, b, c, d = x()print(a, b, c, d)>>>1234
使用*运算符解压缩函数参数
deftest(x, y, z):print(x, y, z)
testDict ={'x':1,'y':2,'z':3}
testList =[10,20,30]
test(*testDict)>>> x y z
test(**testDict)>>>123
test(*testList)>>>102030
使用字典来存储表达式
stdcalc ={'sum':lambda x, y: x + y,'subtract':lambda x, y: x - y
}print(stdcalc['sum'](9,3))>>>12print(stdcalc['subtract'](9,3))>>>6
一行代码计算任何数字的阶乘
import functools
result =(lambda k: functools.reduce(int.__mul__,range(1,k+1),1))(3)print(result)>>>6
找到一个列表中的出现最频繁的值
test =[1,2,3,4,2,2,3,1,4,4,4]print(max(set(test), key=test.count))>>>4
import itertools
test =[[-1,-2],[30,40],[25,35]]print(list(itertools.chain.from_iterable(test)))>>>[-1,-2,30,40,25,35]
如果输入列表中有嵌入的列表或元组作为元素,那么就使用下面这种方法,不过也有个局限,它使用了 for 循环
defunifylist(l_input, l_target):for it in l_input:ifisinstance(it,list):
unifylist(it, l_target)elifisinstance(it,tuple):
unifylist(list(it), l_target)else:
l_target.append(it)return l_target
test =[[-1,-2],[1,2,3,[4,(5,[6,7])]],(30,40),[25,35]]print(unifylist(test,[]))>>>[-1,-2,1,2,3,4,5,6,7,30,40,25,35]