effective python讀書筆記——帶*的表達(dá)式
2021-11-18 07:33 作者:與時(shí)代脫軌的級(jí)數(shù) | 我要投稿
#當(dāng)需要把數(shù)據(jù)拆分賦給變量時(shí):
nums=[2,5,1,7,4,9,8,3,0]
nums.sort(reverse=True)
first=nums[0]
second=nums[1]
others=nums[2:]
print(f"first : {first} second : {second} others : {others}")
#切片法顯得比較亂,還得考慮下標(biāo)
first_1,second_1,*others_1=nums #清晰
print(f"first_1 : {first_1} second_1 : {second_1} others_1 : {others_1}")
#可以捕獲任何一段元素
a,*b,c=nums
print(f"a : {a} b : c : {c}")
#帶星號(hào)的變量至少與一個(gè)普通變量搭配,且單層結(jié)構(gòu)只能出現(xiàn)一次
#如 *d=nums ?*e,*f,g=nums 就會(huì)出錯(cuò)
#多層結(jié)構(gòu)也能用,但是不推薦:
nums_1={'first':(1,2,3,4),'second':(4,5,6)}
((x,(x1,*x2)),(y,(y1,*y2)))=nums_1.items()
print(f'{x} have {x1} and {x2} \n{y} have {y1} and {y2}')
#可生成空列表
short=[1,2]
a,b,*c=short
print(f'{a}----{c}')

標(biāo)簽: