【python基礎(chǔ)】8-序列、集合以及字典數(shù)據(jù)類型

我們?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)一步閱讀

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本節(jié)要介紹的是Python里面常用的幾種數(shù)據(jù)結(jié)構(gòu)。通常情況下,聲明一個(gè)變量只保存一個(gè)值是遠(yuǎn)遠(yuǎn)不夠的,我們需要將一組...
    小黑y99閱讀 65,605評(píng)論 0 9
  • 2018年2月18日 日精進(jìn) 體驗(yàn) 吸收 釋放 分享 轉(zhuǎn)化 九字真言 體驗(yàn)入 找核心 轉(zhuǎn)身用 ...
    凌勝亮閱讀 126評(píng)論 0 0
  • 關(guān)掉朋友圈之后,我并未第一時(shí)間意識(shí)到,但卻是至今最強(qiáng)烈意識(shí)到的一件事就是:不用朋友圈,你就真的沒什么朋友了。 只有...
    樂鈫閱讀 461評(píng)論 0 2
  • 明天早上就要結(jié)一門必修了。 我一點(diǎn)都不想學(xué)習(xí)。 我嘗試過很多很多激勵(lì)自己的方法,要是全部記錄下來都可以作為相關(guān)研...
    dayi閱讀 214評(píng)論 0 0
  • 從相知到相戀,再到分開,時(shí)光在變,感覺在變,最終還是一個(gè)人。 漸漸地,感覺自己不愛了,也或是不敢再愛了,心也許還放...
    笑風(fēng)笑雨閱讀 571評(píng)論 1 0

友情鏈接更多精彩內(nèi)容