python3測試工具開發快速入門教程2數據結構4其他數據結構

數據結構

函數式編程工具

對於列表來講,有三個內置函數非常有用: 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) 爲每個元素調用 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]

函數需要多個參數,可以傳入對應的序列。如果參數和序列數不匹配,則按最短長度來處理。如果傳入的序列長度不匹配,則用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) 先以序列的前兩個元素調用函數function,再以返回值和第三個參數調用,以此類推。比如計算 1 到 10 的整數之和:

#!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

可以傳入第三個參數作爲默認值。如果序列是空就返回默認值。

#!python
>>> def sum(seq):
...     def add(x,y): return x+y
...     return reduce(add, seq, 0)
... 
>>> sum(range(1, 11))
55
>>> sum([])
0

不要像示例這樣定義 sum(),內置的 sum(sequence) 函數更好用。

del 語句

del可基於索引而不是值來刪除元素。:del 語句。與 pop() 方法不同,它不返回值。del 還可以從列表中刪除區間或清空整個列表。例如:

#!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會引發錯誤。

元組和序列

鏈表和字符串有很多通用的屬性,例如索引和切割操作。它們都屬於序列類型(參見 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])

元組在輸出時總是有括號的,嵌套元組可以清晰展示。在輸入時可以沒有括號,清晰起見,建議儘量添加括號。不能給元組的的元素賦值,但可以創建包含可變對象的元組,比如列表。
元組是不可變的,通常用於包含不同類型的元素,並通過解包或索引訪問(collections模塊中namedtuple中可以通過屬性訪問)。列表是可變的,元素通常是相同的類型,用於迭代。
空的括號可以創建空元組;要創建一個單元素元組可以在值後面跟一個逗號單元素元組。醜陋,但是有效。例如:

#!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

等號右邊可以是任何序列,即序列解包。序列解包要求左側的變量數目與序列的元素個數相同。

集合

集合是無序不重複元素的集。基本用法有關係測試和去重。集合還支持 union(聯合),intersection(交),difference(差)和 sysmmetric difference(對稱差集)等數學運算。
大括號或set()函數可以用來創建集合。注意:想要創建空集合只能使用 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'])

類似列表推導式,集合也可以使用推導式:

#!python
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

字典

字典 (參見 Mapping Types — dict )。字典在一些語言中稱爲聯合內存 (associative memories) 或聯合數組 (associative arrays)。字典以key爲索引,key可以是任意不可變類型,通常爲字符串或數值。

可以把字典看做無序的鍵:值對 (key:value對)集合。{}創建空的字典。key:value的格式,以逗號分割。

字典的主要操作是依據key來讀寫值。用 del 可以刪除key:value對。讀不存在的key取值會導致錯誤。

keys() 返回字典中所有關鍵字組成的無序列表。使用 in 可以判斷成員關係。

這裏是使用字典的一個小示例:

#!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() 構造函數可以直接從 key-value 序列中創建字典:

#!python
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

字典推導式可以從任意的鍵值表達式中創建字典:

#!python
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

如果關鍵字都是簡單的字符串,可通過關鍵字參數指定 key-value 對:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

序列和其它類型比較

序列對象可以與相同類型的其它對象比較。比較基於字典序:首先比較前兩個元素,如果不同,就決定了比較的結果;如果相同,就比較後兩個元素,依此類推,直到有序列結束。如果兩個元素是同樣類型的序列,就遞歸比較。如果兩個序列的所有子項都相等則序列相等。如果一個序列是另一個序列的初始子序列,較短的序列就小於另一個。字符串的字典序基於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)

注意可以比較不同類型的對象也是合法的。比較結果是確定的但是比較隨意: 基於類型名(Python未來版本中可能發生變化)排序。因此,列表始終小於字符串,字符串總是小於元組,等等。 不同數值類型按照它們的值比較,所以 0 等於 0.0,等等。

參考資料

計算不同版本人臉識別框的重合面積

現有某圖片,版本1識別的座標爲:(60, 188, 260, 387),版本2識別的座標爲(106, 291, 340, 530)))。格式爲left, top, right, buttom。
請計算:公共的像素總數,版本1的像素總數,版本2的像素總數,版本1的重合面積比例,版本2的重合面積比例.

參考代碼:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技術支持 釘釘羣: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)))

詳細代碼地址

執行

#!python
$ python3 overlap.py 
(14784, 39800, 55926, 0.3714572864321608, 0.2643493187426242)

1羣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章