Python Cookbook之数据结构与算法

数据结构与算法 Data Structure and Arithmetic

注:本文都是抄字于原书《Python Cookbook》,目的是进行Python的初学


目录

1、Q:将序列分解为单独的变量

2、Q:从任意长度的可迭代对象中分解元素

3、Q:保留最后N个元素

4、Q:找到最大/最小的N的元素

5、Q:让字典保持有序

6、Q:让字典键与值翻转

6、Q:找出字典相同点

7、Q:对切片命名,增加代码可读性

8、Q:计算序列中出现次数最多的元素



1、Q:将序列分解为单独的变量


A:任何序列(可迭代序列)都可以经过简单的赋值来分解为单个变量。

test1 = (3,4)
x,y = test1
print ("x=<%d>, y=<%d>" % (x, y))

运行结果:x=<3>, y=<4>

注解:只要对象是可迭代的,都可以执行分解操作。(序列、元祖、列表、字符串、文件、迭代器、生成器)

str1 = 'andy'
a,b,c,d = str1
print("%s,%s,%s,%s" % (a,b,c,d))

运行结果:a,n,d,y


2、Q:从任意长度的可迭代对象中分解元素


A:迭代对象超出赋值对象个数时报错  分解值过多:“ValueError: too many values to unpack (expected 4)”。

#Python 的“*表达式”,但是无论怎样c都是一个列表
str1 = 'andy'
a,b,*c = str1
print("%s,%s,%s" % (a,b,c))
#运行结果:a,n,['d', 'y']

#多个*式的用法(‘*_’或者‘*ign’(ignore)等惯用表示待丢弃的变量)
record = ('Andy', 10, 20, 30, (1, 2, 3, 2018))
name, *_, (*_, year) = record
print("%s,%s" % (name, year))
#运行结果:Andy,2018

3、Q:保留最后N个元素


A:deque(maxlen=N)产生一个固定长度为N的队列,我们经常用它来保存最后几个元素

from collections import deque
q = deque(maxlen = 5)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
print(q)
q.append(6)
print(q)
print(q.pop())
print(q)
print(q.popleft())
print(q)

运行结果:

deque([1, 2, 3, 4, 5], maxlen=5)
deque([2, 3, 4, 5, 6], maxlen=5)
6
deque([2, 3, 4, 5], maxlen=5)
2
deque([3, 4, 5], maxlen=5)


4、Q:找到最大/最小的N的元素


A:heapq模块有两个函数 nlargest()、nsmallest()

import heapq
nums = {1,2,34,-45,65,75,346,32,-40}
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))

portInfo = [
    {'name':'andy', 'price':10.1},
    {'name':'andy1', 'price':10.5},
    {'name':'andy2', 'price':23.5},
    {'name':'andy3', 'price':45.5},
    {'name':'andy4', 'price':15.5}
    ]
print(heapq.nlargest(3, portInfo, key = lambda s: s['price']))
print(heapq.nlargest(3, portInfo, key = lambda s: s['name']))

运行结果:

[346, 75, 65]
[-45, -40, 1]
[{'name': 'andy3', 'price': 45.5}, {'name': 'andy2', 'price': 23.5}, {'name': 'andy4', 'price': 15.5}]
[{'name': 'andy4', 'price': 15.5}, {'name': 'andy3', 'price': 45.5}, {'name': 'andy2', 'price': 23.5}]

#max() min()内建函数

d1 = {'name': 'egon', 'price': 100}
d2 = {'name': 'rdw', 'price': 666}
d3 = {'name': 'zat', 'price': 1}
l1 = [d1, d2, d3]
a = max(l1, key=lambda x: x['name'])
print(a)
b = max(l1, key=lambda x: x['price'])
print(b)

 运行结果:

{'name': 'zat', 'price': 1}
{'name': 'rdw', 'price': 666}


5、Q:让字典保持有序


A:要控制字典中元素的顺序,可以使用collections 模块中的 OrderedDict模块

from collections import OrderedDict
d = OrderedDict()
d['andy1'] = 1
d['andy2'] = 2
d['andy3'] = 3
d['andy4'] = 4
d['andy5'] = 5

for key in d:
    print(key, d[key])

运行结果:

andy1 1
andy2 2
andy3 3
andy4 4
andy5 5


6、Q:让字典键与值翻转


A:使用zip(),场景:我们常见的数据操作只会处理键,而不是值,我们想对值进行排序时则要用到zip()

d = {}
d['andyF'] = 1
d['andyA'] = 2
d['andyC'] = 3
d['andyB'] = 4
d['andyE'] = 5

#普通操作(只能对键进行操作)
print("min(d) is:",min(d))

#求最小的andy
min_andy = min(zip(d.values(),d.keys()))
print("min_andy:",min_andy)
min_andy = max(zip(d.values(),d.keys()))
print("max_andy:",min_andy)

运行结果:

min(d) is: andyA
min_andy: (1, 'andyF')
max_andy: (5, 'andyE') 


6、Q:找出字典相同点

A:使用keys()、items()方法

a = {
    'x' : 1,
    'y' : 2,
    }
b = {
    'x' : 1,
    'y' : 2,
    'z' : 3,    
    }

print(a.keys() & b.keys())
print(b.keys() - a.keys())
print(a.items() & b.items())

运行结果:
{'y', 'x'}
{'z'}
{('x', 1), ('y', 2)}

7、Q:对切片命名,增加代码可读性


A:使用slice()方法创建一个切片对象

test= "012345678"
A = slice(2,4)
print(test[A])

执行结果:
23

8、Q:计算序列中出现次数最多的元素

A:使用collocations中的Counter

from collections  import Counter
words1 = ['a','b','c','a']
Counter(words1).most_common(None)
print(Counter(words1))
print(Counter(words1).most_common(2))

# 支持算数运算
words2 = ['1','b','c','2']
print('------------\n')
print(Counter(words1) + Counter(words2))
print(Counter(words1) - Counter(words2))

运行结果:
Counter({'a': 2, 'b': 1, 'c': 1})
[('a', 2), ('b', 1)]
------------

Counter({'a': 2, 'b': 2, 'c': 2, '1': 1, '2': 1})
Counter({'a': 2})

猜你喜欢

转载自blog.csdn.net/weixin_30069221/article/details/81278547