Python序列元素解壓全面介紹

2021-10-20 04:23:18 字數 3266 閱讀 8472

p =(4

,5)x,y = p

print

(x,y)

輸出: 4 5
data =[,

100,

4.5,

(2021,1

,28)]

name,weight,price,date = data

print

(name,weight,price,date)

name,weight,price,

(year,month,day)

= data

print

(name,weight,price,year,month,day)

**注意:**當變數個數與序列元素數量不匹配時,將出錯

a,b,c =

'abc'

print

(a,b,c)

輸出:a b c
有時需要忽略一些變數,則可以通過下劃線來實現。

name,_,price,_ = data

print

(name,price)

record =

['jenson'

,'[email protected]'

,'+86-020-12345678'

,'+86-13700000001'

]name,email,

*phones = record

print

(name,email,phones)

輸出:jenson [email protected] ['+86-020-12345678', '+86-13700000001']
*head,tail =[1

,2,3

,4,5

,6,7

,8,9

,0]print

(tail)

first,

*last =[1

,2,2

,3,4

,5,6

]print

(first)

輸出:

01

fruits =[(

,4.5),

('pear'

,3.8),

('banana'

,2.5),

('grape'

,12.3)]

for name,

*args in fruits:

if name ==

:print

(,args)

data =[,

100,

4.5,

(2021,1

,28)]

name,

*args,

(year,_,_)

= data

print

(name,year)

def

sum(values)

: head,

*tail = values

return head +

sum(tail)

if tail else head

value =

sum([1

,2,3

,4,5

,6,7

,8,9

,0])

print

(value)

輸出45
保留最後n個元素,可以使用collection.deque來實現

from collections import deque

defkeep_last_n_elem

(values,pattern,history=5)

: previous = deque(maxlen=history)

for value in values:

if value in pattern:

yield value,previous

with

open

('datas/somefile.txt'

)as f:

for line,prev in keep_last_n_elem(f,

'python'):

print

(len

(prev)

)for pline in prev:

print

(pline,end='')

print

(line,end='')

print

('-'*20

)

可以通過使用heapq的nlargest和nsmallest實現。

import heapq

nums =[1

,8,2

,23,7

,-4,

18,23,

42,37,

2]print

(heapq.nlargest(

3, nums)

)print

(heapq.nsmallest(

3, nums)

)

輸出:

[42, 37, 23]

[-4, 1, 2]

對於複雜的資料,同樣可以實現

portfolio =[,

,,,,

] cheap = heapq.nsmallest(

3, portfolio, key=

lambda s: s[

'price'])

print

(cheap)

expensive = heapq.nlargest(

3, portfolio, key=

lambda s: s[

'price'])

print

(expensive)

輸出:[, , ]

[, , ]

Python3 解壓序列

一 普遍情況 x,y,z 1,2,3print x x x 1 print y y y 2 print z z z 3二 針對元祖 name qiaobushi wanglihong leibushi x,y,z name print name print x x print y y print z...

Python過濾序列元素的方法

問題 你有乙個資料序列,想利用一些規則從中提取出需要的值或者是縮短序列 解決方案 最簡單的過濾序列元素的方法就是使用列表推導。比如 mylist 1,4,5,10,7,2,3,1 n for n in mylist if n 0 1,4,10,2,3 n for n in mylist if n 0...

Python 統計序列中元素出現次數

import sys import random from collections import counter reload sys sys.setdefaultencoding utf 8 data list random.randint 1,20 for in range 10 從1 20隨機...