1.1将序列分解为单独变量
data=['ame',123,20.3,(1,2,3),[1,2]]
a,b,c,d,e=data
print(a,b,c,d,e)
a,b=e
print(a,b)
输出:
ame 123 20.3 (1, 2, 3) [1, 2]
1 2
不仅仅是元组和列表,只要对象可迭代,则可分解。
s='hel'
a,b,c=s
print(a,"----",b,"----",c)
输出:
h ---- e ---- l
遇到可以丢弃的值,则可使用以下方法
_,a,_=s
print(a)
输出:
e
1.2从任意长度的可迭代对象中分解元素
data=['ame',123,20.3,(1,2,3),[1,2]]
head,*mid,tail=data
print(mid)
输出:
[123, 20.3, (1, 2, 3)]
data=['ame',123,20.3,(1,2,3),[1,2]]
head,mid,*tail=data
print(mid)
输出:
123
data=['ame',123,20.3,(1,2,3),[1,2]]
head,mid,*tail=data
print(mid)
a,*b=head
print(b)
输出:
123
[‘m’, ‘e’]
应用:计算除去最高分最低分后的平均值
score=[56,66,76,95,85,45]
score.sort()
print(score)
low,*mid,hig=score
print(sum(mid)/len(mid))
输出:
[45, 56, 66, 76, 85, 95]
70.75
应用:zz操作系列
path = "C:\\Users\\w1\\IdeaProjects\\untitled6\\src\\com\\company\\Main.java"
disk,*pa,name=path.split('\\')
print(pa)
输出:
[‘Users’, ‘w1738’, ‘IdeaProjects’, ‘untitled6’, ‘src’, ‘com’, ‘company’]
1.3保存N个元素
from collections import deque
def search(lines,pattern,history=1):
previous_line=deque(maxlen=history)
for line in lines:
if pattern in line: #所要匹配的字符在line中
yield line, previous_line
previous_line.append(line)
if __name__ == '__main__':
filename="a.txt"
with open(filename) as f: #打开文件,f以行为单位
for line, prevlines in search(f,'new'):
for pline in prevlines:
print(pline,end='') #print默认在输出后添加换行,end=''将换行替换为空字符串
print(line,end='')
print('-'*20)
1.4找到最大或最小的N个元素
import heapq
nums = [26,42 ,31 ,56 ,48 ,19 ,66 ,-1 , 12]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(2,nums))
#处理更复杂的数据结构
por=[
{'name':'IBM','share':66,'price':230.1},
{'name':'csco','share':56,'price':21.7},
{'naem':'sdew','share':654,'price':97.66},
{'naem': 'sdew', 'share': 654, 'price': 17.66},
{'naem': 'sop', 'share': 424, 'price': 34.6},
{'naem': 'siyuu', 'share': 14, 'price': 80.66},
]
print(heapq.nlargest(3,por,key=lambda a:a['price']))