Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 常見數據結構整理:序列、字典與集合

Python 的常見數據結構可以統稱為容器(container),主要分三類:序列(列表、元組、字串)、映射(字典)與集合(set)。

一、序列

序列中每個元素都有自己的編號。Python 有六種內建序列,最常用的是列表與元組,其餘包括字串、Unicode 字串、buffer 物件與 xrange 物件。

1. 列表

列表最大的特點是可變——這正是它與字串、元組的關鍵差別。

list1 = ['hello', 'world']
print list1
list2 = [1, 2, 3]
print list2

# 輸出
['hello', 'world']
[1, 2, 3]

這種寫法與 JavaScript 的陣列幾乎一樣。另外,list(其實是型別而非函數)很適合把字串拆成列表:

list3 = list("hello")
print list3

# 輸出
['h', 'e', 'l', 'l', 'o']

2. 元組

元組也是序列,唯一不同是不能修改。

t1 = 1, 2, 3
t2 = "jeffreyzhao", "cnblogs"
t3 = (1, 2, 3, 4)
t4 = ()
t5 = (1,)
print t1, t2, t3, t4, t5

# 輸出
(1, 2, 3) ('jeffreyzhao', 'cnblogs') (1, 2, 3, 4) () (1,)

從例子可以歸納四點:逗號分隔即可自動成元組;通常用圓括號括起;空元組寫成 ();只有一個元素時必須補上逗號。

tuple 的用法與 list 幾乎相同,接收一個序列並轉為元組,若參數本來就是元組則原樣返回:

t1 = tuple([1, 2, 3])
t2 = tuple("jeff")
t3 = tuple((1, 2, 3))
print t1
print t2
print t3
t4 = tuple(123)
print t4

# 輸出
(1, 2, 3)
('j', 'e', 'f', 'f')
(1, 2, 3)

Traceback (most recent call last):
  File "F:\Python\test.py", line 7, in <module>
    t4=tuple(123)
TypeError: 'int' object is not iterable

3. 字串

str1 = 'Hello world'
print str1
print str1[0]
for c in str1:
    print c

格式化用百分比運算子完成:

str1 = 'Hello,%s' % 'world.'
print str1

strs = ('Hello', 'world')   # 元組
str1 = '%s,%s' % strs
print str1

d = {'h': 'Hello', 'w': 'World'}   # 字典
str1 = '%(h)s,%(w)s' % d
print str1

# 輸出
Hello,world
Hello,World

若元組是表達式的一部分,必須用圓括號括起來,否則會報 TypeError: not enough arguments for format string。要輸出 % 本身,寫成 %%:

str1 = '%s%%' % 100
print str1   # 100%

數值格式化常需控制寬度與精度:

from math import pi
str1 = '%.2f' % pi         # 精度 2
print str1
str1 = '%10f' % pi         # 欄位寬 10
print str1
str1 = '%10.2f' % pi       # 寬 10、精度 2
print str1

# 輸出
3.14
 3.141593
    3.14

另一種做法是 string 模組的模板字串,風格接近 UNIX Shell 的變數替換:

from string import Template
str1 = Template('$x,$y!')
str1 = str1.substitute(x='Hello', y='world')
print str1   # Hello,world!

# 替換欄位是單詞一部分時用 ${} 標明結尾
str1 = Template('Hello,w${x}d!')
str1 = str1.substitute(x='orl')
print str1   # Hello,world!

# 輸出 $ 用 $$
str1 = Template('$x$$')
str1 = str1.substitute(x='100')
print str1   # 100$

# 也可以傳字典
d = {'h': 'Hello', 'w': 'world'}
str1 = Template('$h,$w!')
str1 = str1.substitute(d)
print str1   # Hello,world!

4. 通用序列操作

從列表、元組、字串可以抽出共同操作:索引、分片、相加、相乘、成員檢查,再加上 len、max、min。

索引從 0 開始,也支援負數從右往左數(-1 是最後一個):

str1 = 'Hello'
nums = [1, 2, 3, 4]
t1 = (123, 234, 345)
print str1[0], nums[1], t1[2]    # H 2 345
print str1[-1], nums[-2], t1[-3]  # o 3 123

分片用冒號分隔兩個索引,可再加步長:

nums = range(10)
print nums                   # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print nums[1:5]            # [1, 2, 3, 4]
print nums[6:10]            # [6, 7, 8, 9]
print nums[1:]              # [1, 2, ..., 9]
print nums[-3:-1]           # [7, 8]
print nums[-3:]             # [7, 8, 9](含結尾元素)
print nums[:]               # 複製整個序列

print nums[0:10]           # 預設步長 1
print nums[0:10:2]         # [0, 2, 4, 6, 8]
print nums[0:10:3]         # [0, 3, 6, 9]
print nums[0:10:-2]         # []

相加與相乘只能發生在同類序列之間,混用會拋 TypeError:

print 'Hello' + ' world'     # Hello world
print [1, 2, 3] + [2, 3, 4]  # [1, 2, 3, 2, 3, 4]
print [None] * 10            # 十個 None
print 'Hello' * 2            # HelloHello

成員資格用 in,注意字串比對區分大小寫:'h' in 'Hello' 為 False,'H' in 'Hello' 為 True。len/max/min 分別回傳元素數量、最大值與最小值。

二、映射(字典)

映射的每個元素有一個名字,也就是鍵。字典(散列表)是 Python 唯一內建的映射型別。

鍵可以是數字、字串或元組,必須唯一,且必須是不可變型別——所以列表與集合不能當鍵:

list1 = ["hello,world"]
set1 = set([123])
d = {}
d[1] = 1
print d         # {1: 1}
d[list1] = "Hello world."
d[set1] = 123

Traceback (most recent call last):
  File "F:\Python\test.py", line 6, in <module>
    d[list1]="Hello world."
TypeError: unhashable type: 'list'

字典還有兩個便利之處:即使鍵不存在也能直接賦值,字典會自動新增該項;而 item in d 檢查的是鍵,不是值。更多內建操作可查官方文件。

三、集合

集合自 Python 2.3 引入,可由任何可迭代物件建構:

strs = set(['jeff', 'wong', 'cnblogs'])
nums = set(range(10))

要點如下:

  • 副本被忽略:集合主要用於成員檢查,重複元素自動去重。
  • 順序隨意:可以把它理解成沒有 value 的字典。
set1 = set([0, 1, 2, 3, 0, 1, 2, 3, 4, 5])
set2 = set([0, 1, 2, 3, 4, 5])
print set1   # set([0, 1, 2, 3, 4, 5])
print set2   # set([0, 1, 2, 3, 4, 5])

常用運算:並集用 union() 或 |,交集用 &,還有 <=、>=、差集 -、copy()、issubset() 等,都不會改動原集合:

set1 = set([1, 2, 3])
set2 = set([2, 3, 4])
set3 = set1.union(set2)   # 或 set1 | set2
print set3                # set([1, 2, 3, 4])

set3 = set1 & set2
print set3                # set([2, 3])
print set3.issubset(set1)    # True

set4 = set1.copy()
print set4 is set1          # False

add 與 remove 的行為和序列類似,但移除不存在的元素會拋 KeyError:

set1 = set([1])
set1.add(2)
set1.remove(2)
print 29 in set1       # False
set1.remove(29)        # KeyError: 29

集合可變,因此不能當字典的鍵,也不能包含另一個集合。需要不可變集合時用 frozenset:

set1 = set([1])
set2 = set([2])
set1.add(set2)                # TypeError: unhashable type: 'set'
set1.add(frozenset(set2))
print set1                     # set([1, frozenset([2])])
Copyright © Linux教程網 All Rights Reserved