數(shù)據(jù)結(jié)構(gòu)
函數(shù)式編程工具
對于列表來講,有三個內(nèi)置函數(shù)非常有用: filter(), map(), 以及reduce()。
filter(function, sequence)返回function(item)為true的子序列。會盡量返回和sequence相同的類型)。sequence是string或者tuple時返回相同類型,其他情況返回list 。實例:返回能被3或者5整除的序列:
#!python
>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> list(filter(f, range(2, 25)))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
map(function, sequence) 為每個元素調(diào)用 function(item),并將返回值組成一個列表返回。例如計算立方:
#!python
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
函數(shù)需要多個參數(shù),可以傳入對應(yīng)的序列。如果參數(shù)和序列數(shù)不匹配,則按最短長度來處理。如果傳入的序列長度不匹配,則用None不全。例如:
#!python
>>> seq = range(8)
>>> def add(x, y): return x+y
...
>>> list(map(add, seq, seq))
[0, 2, 4, 6, 8, 10, 12, 14]
>>> seq1 = range(8)
>>> seq2 = range(10)
>>> list(map(add, seq1, seq2))
[0, 2, 4, 6, 8, 10, 12, 14]
>>> list(map(add, seq1, seq, seq2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-2ddf805a1583> in <module>()
----> 1 list(map(add, seq1, seq, seq2))
TypeError: add() takes 2 positional arguments but 3 were given
reduce(function, sequence) 先以序列的前兩個元素調(diào)用函數(shù)function,再以返回值和第三個參數(shù)調(diào)用,以此類推。比如計算 1 到 10 的整數(shù)之和:
#!python
>>> from functools import reduce
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
如果序列中只有一個元素,就返回該元素,如果序列是空的,就報異常TypeError:
#!python
>>> reduce(add, [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value
>>> reduce(add, [3])
3
可以傳入第三個參數(shù)作為默認值。如果序列是空就返回默認值。
#!python
>>> def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
>>> sum(range(1, 11))
55
>>> sum([])
0
不要像示例這樣定義 sum(),內(nèi)置的 sum(sequence) 函數(shù)更好用。
del 語句
del可基于索引而不是值來刪除元素。:del 語句。與 pop() 方法不同,它不返回值。del 還可以從列表中刪除區(qū)間或清空整個列表。例如:
#!python
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
del 也可以刪除整個變量:
#!python
>>> del a
此后再引用a會引發(fā)錯誤。
元組和序列
鏈表和字符串有很多通用的屬性,例如索引和切割操作。它們都屬于序列類型(參見 Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange https://docs.python.org/2/library/stdtypes.html#typesseq)。Python在進化時也可能會加入其它的序列類型。
元組由逗號分隔的值組成:
#!python
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
元組在輸出時總是有括號的,嵌套元組可以清晰展示。在輸入時可以沒有括號,清晰起見,建議盡量添加括號。不能給元組的的元素賦值,但可以創(chuàng)建包含可變對象的元組,比如列表。
元組是不可變的,通常用于包含不同類型的元素,并通過解包或索引訪問(collections模塊中namedtuple中可以通過屬性訪問)。列表是可變的,元素通常是相同的類型,用于迭代。
空的括號可以創(chuàng)建空元組;要創(chuàng)建一個單元素元組可以在值后面跟一個逗號單元素元組。丑陋,但是有效。例如:
#!python
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
>>> ('hello',)
('hello',)
語句 t = 12345, 54321, 'hello!' 是 元組打包 (tuple packing)的例子:值12345,54321 和 'hello!' 被封裝進元組。其逆操作如下:
#!python
>>> x, y, z = t
等號右邊可以是任何序列,即序列解包。序列解包要求左側(cè)的變量數(shù)目與序列的元素個數(shù)相同。
集合
集合是無序不重復(fù)元素的集。基本用法有關(guān)系測試和去重。集合還支持 union(聯(lián)合),intersection(交),difference(差)和 sysmmetric difference(對稱差集)等數(shù)學運算。
大括號或set()函數(shù)可以用來創(chuàng)建集合。注意:想要創(chuàng)建空集合只能使用 set() 而不是 {}。
#!python
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
類似列表推導(dǎo)式,集合也可以使用推導(dǎo)式:
#!python
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
字典
字典 (參見 Mapping Types — dict )。字典在一些語言中稱為聯(lián)合內(nèi)存 (associative memories) 或聯(lián)合數(shù)組 (associative arrays)。字典以key為索引,key可以是任意不可變類型,通常為字符串或數(shù)值。
可以把字典看做無序的鍵:值對 (key:value對)集合。{}創(chuàng)建空的字典。key:value的格式,以逗號分割。
字典的主要操作是依據(jù)key來讀寫值。用 del 可以刪除key:value對。讀不存在的key取值會導(dǎo)致錯誤。
keys() 返回字典中所有關(guān)鍵字組成的無序列表。使用 in 可以判斷成員關(guān)系。
這里是使用字典的一個小示例:
#!python
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
dict() 構(gòu)造函數(shù)可以直接從 key-value 序列中創(chuàng)建字典:
#!python
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
字典推導(dǎo)式可以從任意的鍵值表達式中創(chuàng)建字典:
#!python
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
如果關(guān)鍵字都是簡單的字符串,可通過關(guān)鍵字參數(shù)指定 key-value 對:
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
序列和其它類型比較
序列對象可以與相同類型的其它對象比較。比較基于字典序:首先比較前兩個元素,如果不同,就決定了比較的結(jié)果;如果相同,就比較后兩個元素,依此類推,直到有序列結(jié)束。如果兩個元素是同樣類型的序列,就遞歸比較。如果兩個序列的所有子項都相等則序列相等。如果一個序列是另一個序列的初始子序列,較短的序列就小于另一個。字符串的字典序基于ASCII。
#!python
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
注意可以比較不同類型的對象也是合法的。比較結(jié)果是確定的但是比較隨意: 基于類型名(Python未來版本中可能發(fā)生變化)排序。因此,列表始終小于字符串,字符串總是小于元組,等等。 不同數(shù)值類型按照它們的值比較,所以 0 等于 0.0,等等。
參考資料
- 討論qq群144081101 591302926 567351477 釘釘免費群21745728
- 本文最新版本地址
- 本文涉及的python測試開發(fā)庫 謝謝點贊!
- 本文相關(guān)海量書籍下載
- 本文源碼地址
計算不同版本人臉識別框的重合面積
現(xiàn)有某圖片,版本1識別的坐標為:(60, 188, 260, 387),版本2識別的坐標為(106, 291, 340, 530)))。格式為left, top, right, buttom。
請計算:公共的像素總數(shù),版本1的像素總數(shù),版本2的像素總數(shù),版本1的重合面積比例,版本2的重合面積比例.
參考代碼:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術(shù)支持 釘釘群:21745728(可以加釘釘pythontesting邀請加入)
# qq群:144081101 591302926 567351477
# CreateDate: 2018-6-07
def get_area(pos):
left, top, right, buttom = pos
left = max(0, left)
top = max(0, top)
width = right - left
height = buttom - top
return (width*height, left, top, right, buttom)
def overlap(pos1, pos2):
area1, left1, top1, right1, buttom1 = get_area(pos1)
area2, left2, top2, right2, buttom2 = get_area(pos2)
left = max(left1, left2)
top = max(top1, top2)
left = max(0, left)
top = max(0, top)
right = min(right1, right2)
buttom = min(buttom1, buttom2)
if right <= left or buttom <= top:
area = 0
else:
area = (right - left)*(buttom - top)
return (area, area1, area2, float(area)/area1, float(area)/area2)
print(overlap((60, 188, 260, 387), (106, 291, 340, 530)))
執(zhí)行
#!python
$ python3 overlap.py
(14784, 39800, 55926, 0.3714572864321608, 0.2643493187426242)
1群