我們?cè)谇懊嬲鹿?jié)已經(jīng)看到過字符串、區(qū)間、列表等序列類型。元組是另外一中序列類型。這一章我們學(xué)習(xí)更多關(guān)于字符串、元組、字典和集合的操作。
字符串
- 我們之前看到在列表中使用的索引也可以應(yīng)用于字符串
- 因?yàn)樽址豢勺冮L(zhǎng),它們不能像列表一樣修改
>>> book = "Alchemist"
>>> book[0]
'A'
>>> book[3]
'h'
>>> book[-1]
't'
>>> book[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> book[2:6]
'chem'
>>> book[:5]
'Alche'
>>> book[5:]
'mist'
>>> book[::-1]
'tsimehclA'
>>> book[:]
'Alchemist'
>>> list(book)
['A', 'l', 'c', 'h', 'e', 'm', 'i', 's', 't']
>>> import string
>>> string.ascii_lowercase[:10]
'abcdefghij'
>>> list(string.digits)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
- 字符串循環(huán)操作
>>> book
'Alchemist'
>>> for char in book:
... print(char)
...
A
l
c
h
e
m
i
s
t
- 其他操作
>>> book
'Alchemist'
>>> len(book)
9
>>> book.index('A')
0
>>> book.index('t')
8
>>> 'A' in book
True
>>> 'B' in book
False
>>> 'z' not in book
True
>>> min('zealous')
'a'
>>> max('zealous')
'z'
元組
- 元素跟列表相似,但是不可變長(zhǎng),在其他場(chǎng)景中很有用
- 單一的元素可變長(zhǎng)/不變長(zhǎng)
>>> north_dishes = ('Aloo tikki', 'Baati', 'Khichdi', 'Makki roti', 'Poha')
>>> north_dishes
('Aloo tikki', 'Baati', 'Khichdi', 'Makki roti', 'Poha')
>>> north_dishes[0]
'Aloo tikki'
>>> north_dishes[-1]
'Poha'
>>> north_dishes[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> north_dishes[::-1]
('Poha', 'Makki roti', 'Khichdi', 'Baati', 'Aloo tikki')
>>> north_dishes[0] = 'Poori'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
- 示例操作
>>> 'roti' in north_dishes
False
>>> 'Makki roti' in north_dishes
True
>>> len(north_dishes)
5
>>> min(north_dishes)
'Aloo tikki'
>>> max(north_dishes)
'Poha'
>>> for dish in north_dishes:
... print(dish)
...
Aloo tikki
Baati
Khichdi
Makki roti
Poha
- 元組用于處理多個(gè)變量分配(賦值)和在函數(shù)中返回多個(gè)值
- 在使用
enumerate用于迭代列表時(shí)我們已經(jīng)看過例子了
- 在使用
>>> a = 5
>>> b = 20
>>> a, b = b, a
>>> a
20
>>> b
5
>>> c = 'foo'
>>> a, b, c = c, a, b
>>> a
'foo'
>>> b
20
>>> c
5
>>> def min_max(arr):
... return min(arr), max(arr)
...
>>> min_max([23, 53, 1, -34, 9])
(-34, 53)
- 并不總需要使用
()
>>> words = 'day', 'night'
>>> words
('day', 'night')
>>> coordinates = ((1,2), (4,3), (92,3))
>>> coordinates
((1, 2), (4, 3), (92, 3))
>>> prime = [2, 3, 5, 7, 11]
>>> prime_tuple = tuple((idx + 1, num) for idx, num in enumerate(prime))
>>> prime_tuple
((1, 2), (2, 3), (3, 5), (4, 7), (5, 11))
- 將其他類型轉(zhuǎn)換為元組
- 與
list()相似
- 與
>>> tuple('books')
('b', 'o', 'o', 'k', 's')
>>> a = [321, 899.232, 5.3, 2, 1, -1]
>>> tuple(a)
(321, 899.232, 5.3, 2, 1, -1)
- 數(shù)據(jù)類型可用多種方式混合和匹配
>>> a = [(1,2), ['a', 'b'], ('good', 'bad')]
>>> a
[(1, 2), ['a', 'b'], ('good', 'bad')]
>>> b = ((1,2), ['a', 'b'], ('good', 'bad'))
>>> b
((1, 2), ['a', 'b'], ('good', 'bad'))
集合
- 集合是無序的對(duì)象集
- 可變數(shù)據(jù)類型
- 通常用于保持唯一的序列、執(zhí)行集合操作(像交、并、差等等)
>>> nums = {3, 2, 5, 7, 1, 6.3}
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> primes = {3, 2, 11, 3, 5, 13, 2}
>>> primes
{2, 3, 11, 13, 5}
>>> nums.union(primes)
{1, 2, 3, 5, 6.3, 7, 11, 13}
>>> primes.difference(nums)
{11, 13}
>>> nums.difference(primes)
{1, 6.3, 7}
- 示例操作
>>> len(nums)
6
>>> nums[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>> book
'Alchemist'
>>> set(book)
{'i', 'l', 's', 'A', 'e', 'h', 'm', 't', 'c'}
>>> set([1, 5, 3, 1, 9])
{1, 9, 3, 5}
>>> list(set([1, 5, 3, 1, 9]))
[1, 9, 3, 5]
>>> nums = {1, 2, 3, 5, 6.3, 7}
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> nums.pop()
1
>>> nums
{2, 3, 5, 6.3, 7}
>>> nums.add(1)
>>> nums
{1, 2, 3, 5, 6.3, 7}
>>> 6.3 in nums
True
>>> for n in nums:
... print(n)
...
1
2
3
5
6.3
7
字典
- 字典類型被看作無序的鍵值對(duì)或有名字的元素列表
>>> marks = {'Rahul' : 86, 'Ravi' : 92, 'Rohit' : 75}
>>> marks
{'Ravi': 92, 'Rohit': 75, 'Rahul': 86}
>>> fav_books = {}
>>> fav_books['fantasy'] = 'Harry Potter'
>>> fav_books['detective'] = 'Sherlock Holmes'
>>> fav_books['thriller'] = 'The Da Vinci Code'
>>> fav_books
{'thriller': 'The Da Vinci Code', 'fantasy': 'Harry Potter', 'detective': 'Sherlock Holmes'}
>>> marks.keys()
dict_keys(['Ravi', 'Rohit', 'Rahul'])
>>> fav_books.values()
dict_values(['The Da Vinci Code', 'Harry Potter', 'Sherlock Holmes'])
- 循環(huán)和打印
>>> for book in fav_books.values():
... print(book)
...
The Da Vinci Code
Harry Potter
Sherlock Holmes
>>> for name, mark in marks.items():
... print(name, mark, sep=': ')
...
Ravi: 92
Rohit: 75
Rahul: 86
>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(fav_books)
{ 'detective': 'Sherlock Holmes',
'fantasy': 'Harry Potter',
'thriller': 'The Da Vinci Code'}
- 修改字典和示例操作
>>> marks
{'Ravi': 92, 'Rohit': 75, 'Rahul': 86}
>>> marks['Rajan'] = 79
>>> marks
{'Ravi': 92, 'Rohit': 75, 'Rahul': 86, 'Rajan': 79}
>>> del marks['Ravi']
>>> marks
{'Rohit': 75, 'Rahul': 86, 'Rajan': 79}
>>> len(marks)
3
>>> fav_books
{'thriller': 'The Da Vinci Code', 'fantasy': 'Harry Potter', 'detective': 'Sherlock Holmes'}
>>> "fantasy" in fav_books
True
>>> "satire" in fav_books
False
- 字典由列表組成并使用隨機(jī)模塊
- 任何對(duì)單個(gè)列表的改變會(huì)反映在字典中
-
keys()方法的輸出必須改變?yōu)橄?code>list或者tuple這樣的序列類型傳入random.choice
>>> north = ['aloo tikki', 'baati', 'khichdi', 'makki roti', 'poha']
>>> south = ['appam', 'bisibele bath', 'dosa', 'koottu', 'sevai']
>>> west = ['dhokla', 'khakhra', 'modak', 'shiro', 'vada pav']
>>> east = ['hando guri', 'litti', 'momo', 'rosgulla', 'shondesh']
>>> dishes = {'North': north, 'South': south, 'West': west, 'East': east}
>>> rand_zone = random.choice(tuple(dishes.keys()))
>>> rand_dish = random.choice(dishes[rand_zone])
>>> print("Try the '{}' speciality '{}' today".format(rand_zone, rand_dish))
Try the 'East' speciality 'rosgulla' today
進(jìn)一步閱讀