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]