欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python序列元素解压全面介绍

程序员文章站 2022-05-29 16:49:18
...

Python序列元素解压全面介绍

1、将序列元素解压到单独变量

1.1、简单元组解压

p = (4,5)
x,y = p
print(x,y)
输出: 4 5

1.2、复杂数据结构解压

data = ['Apple',100,4.5,(2021,1,28)]
name,weight,price,date = data
print(name,weight,price,date)
输出:Apple 100 4.5 (2021, 1, 28)
name,weight,price,(year,month,day) = data
print(name,weight,price,year,month,day)
输出:Apple 100 4.5 2021 1 28

**注意:**当变量个数与序列元素数量不匹配时,将出错

1.3、字符串解压

a,b,c = 'abc'
print(a,b,c)
输出:a b c

1.4、忽略变量

有时需要忽略一些变量,则可以通过下划线来实现。

name,_,price,_ = data
print(name,price)
输出:Apple 4.5

2、从任意长度可遍历序列解压元素

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']

2.1、获取最后一个元素和第一个元素

*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)
输出:
    0
    1

2.2、过滤元素

fruits = [('apple',4.5),('pear',3.8),('banana',2.5),('grape',12.3)]
for name,*args in fruits:
    if name == 'apple':
        print('price of apple = ',args)
输出:price of apple =  [4.5]

2.3、忽略多个元素

data = ['Apple',100,4.5,(2021,1,28)]
name,*args,(year,_,_) = data
print(name,year)
输出:Apple 2021

2.4、递归调用

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

3、保留最后N个元素

保留最后N个元素,可以使用collection.deque来实现

	from collections import deque
	def keep_last_n_elem(values,pattern,history=5):
        previous = deque(maxlen=history)
        for value in values:
            if value in pattern:
                yield value,previous
            previous.append(value)
        
    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)

4、查找最大和最小N个元素

可以通过使用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 = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
    print(cheap)
    expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
    print(expensive)
输出:[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]
    [{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}]