1. 程式人生 > 其它 >大爽Python入門教程 2-3 字串,列表,字典

大爽Python入門教程 2-3 字串,列表,字典

大爽Python入門公開課教案
點選檢視教程總目錄

除了通用的序列方法,
列表和字串還有些自己的專屬方法。
後面介紹有些是英中文對照介紹(英文來自官方文件),
便於大家更深入的去理解其意思。

靈活的建立

建立空字串,空列表,空字典的基礎寫法

# 建立空字串
s = ''
# 建立空列表
l = []
# 建立空字典
d = {}

使用內建方法來建立空字串,空列表,空字典

# 建立空字串
s = str()
# 建立空列表
l = list()
# 建立空字典
d = dict()

字串,列表,還可以通過轉換其他型別資料得到

>>> s1 = str(1)
>>> s2 = str((1,2,3))
>>> s2
'(1, 2, 3)'
>>> s3 = str(["a", "b"])
>>> s3
"['a', 'b']"
>>> l1 = list("abcde")
>>> l1
['a', 'b', 'c', 'd', 'e']
>>> l2 = list((1,2,3))
>>> l2
[1, 2, 3]

注:字典資料結構比較特殊,匹配的可以用於轉換的資料型別,
我好像還沒看到過。

字串方法

字串的方法繁多,
這裡只介紹最基礎常用且適合現階段的。
未來會再拓展補充

  • str.replace(old, new):
    Return a copy of the string with all occurrences of substring old replaced by new.
    返回字串的副本,其中出現的所有子字串old都將被替換為new
  • str.split(sep=None):
    Return a list of the words in the string, using sep as the delimiter string.
    返回一個由字串內單片語成的列表,使用sep
    作為分隔字串。
    (如果sep未指定或為None,則會應用另一種拆分演算法:連續的空格會被視為單個分隔符。如果字串包含字首或字尾空格的話,返回結果將不包含開頭或末尾的空字串。)
  • str.join(iterable):
    Return a string which is the concatenation of the strings in iterable.
    A TypeError will be raised if there are any non-string values in iterable.
    The separator between elements is the string providing this method.
    返回一個字串,該字串為用原字串拼接(分隔)可迭代物件iterable
    的項得到。
    (iterable,可迭代物件,序列屬於可迭代物件)
    如果iterable中存在任何非字串值,則會報錯TypeError
    呼叫該方法的字串將作為可迭代物件的元素之間的分隔。
>>> "12301530133".replace("0", " ")
'123 153 133'
>>> "a > b > c".replace(">", "<")
'a < b < c'
>>> "old words, old songs".replace("old", "new")
'new words, new songs'
>>> "math music   history ".split()
['math', 'music', 'history']
>>> "li hua,zhang san,li ming".split(",")
['li hua', 'zhang san', 'li ming']
>>> "math music   history ".split()
['math', 'music', 'history']
>>> "12:30:05".split(":")
['12', '30', '05']
>>> " ".join(['math', 'music', 'history'])
'math music history'
>>> "-".join(['2020', '1', '1'])
'2020-1-1'
>>> "-".join("abcde")
'a-b-c-d-e'

列表方法

超常用

list.append(item):
Add an item to the end of the list.
在列表的末尾新增item

示例

>>> courses = []
>>> courses.append("Math")
>>> courses.append("English")
>>> courses
['Math', 'English']
>>> courses.append("Music")
>>> courses
['Math', 'English', 'Music']

這個超常用的需要專門記一下。
下面常用的看一下就好,有個概念就行。
後面用的時候會查就行。
有的用的多了,自然也就記住了。

常用

  • list.insert(index, item):
    Insert an item at a given position.
    在給定位置插入itemindex是位置的索引,。
  • list.remove(item):
    Remove the first item from the list whose value is equal to x.
    It raises a ValueError if there is no such item.
    從列表中刪除item,有多個相同的item則只刪除第一個,沒有item則報錯ValueError
  • list.pop(index=-1):
    Remove the item at the given position in the list, and return it.
    If no index is specified, a.pop() removes and returns the last item in the list.
    刪除列表中給定位置的項,index為該位置的索引,然後將其值返回。
    如果未指定索引,將刪除並返回列表中的最後一項。

使用示例

>>> nums = [9, 12, 10, 12, 15]
>>> nums.insert(0, 20)
>>> nums
[20, 9, 12, 10, 12, 15]
>>> nums.insert(2, 15)
>>> nums
[20, 9, 15, 12, 10, 12, 15]
>>> nums.remove(20)
>>> nums
[9, 15, 12, 10, 12, 15]
>>> nums.remove(15)
>>> nums
[9, 12, 10, 12, 15]
>>> nums.pop()
15
>>> nums
[9, 12, 10, 12]
>>> nums.pop(2)
10
>>> nums
[9, 12, 12]

更多方法(感興趣可以拓展):
more-on-lists

字典

相似與不同

字典不同於序列。
字典是一個又一個鍵值對key:value組成。
雖然同樣用方括號,
dict[key]的方括號中的是鍵key
而不是序列的索引index
字典不支援序列的切片操作的。

dict[key]能得到key對應的value
如果字典中不存在key這個鍵,則會報錯KeyError

修改某個鍵值對的值,可以使用dict[key]=new_value
無法直接修改鍵值對的鍵(只能刪去這個鍵值對,再新增新的)

字典也可以使用len(dict)函式得到其鍵值對的個數。

常用方法

  • dict.get(key, default):
    Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    如果字典中存在key,則返回key對應的值,否則返回default
    如果default未給出則預設為None,因而此方法絕不會引發KeyError

  • dict.keys(key, default):
    Return a new view of the dictionary’s keys.
    返回由字典鍵組成的一個新的view物件。

  • dict.items(key, default):
    Return a new view of the dictionary’s items ((key, value) pairs).
    返回由字典項(鍵值對,元組格式)組成的一個新的view物件。

下面介紹兩個相關的但不太常用的方法

  • dict.values(key, default):
    Return a new view of the dictionary’s values.
    返回由字典值組成的一個新的view物件。
  • dict.pop(key, default):
    If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
    如果key存在於字典中,則將其移除並返回其值,否則返回 default。如果default未給出且key不存在於字典中,則會引發KeyError

這兩者不太常用,大多數練習題或實踐很少光取字典的值,
也很少刪除字典的鍵值對。

dict.keys(), dict.values()dict.items()方法都會返回view物件。
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
該物件提供字典條目的一個動態檢視,這意味著當字典改變時,檢視物件也會相應改變。

目前對該物件只需要瞭解以下三點即可

  • 這個物件可以迭代(即可以使用for迴圈遍歷)。
  • 這個物件是動態的,當字典改變時,其內部會跟著邊。
  • 這個物件不支援序列的索引操作,想要用索引操作可以用list()方法將其轉換成列表。轉換後的列表不會跟隨字典變化。

使用示例

>>> ages = {"A": 18, "B": 20, "C": 26}
>>> len(ages)
3
>>> ages["A"]
18
>>> ages["D"]
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    ages["D"]
KeyError: 'D'
>>> ages.get("A")
18
>>> ages.get("D")
>>> keys = ages.keys()
>>> keys
dict_keys(['A', 'B', 'C'])
>>> items = ages.items()
>>> items
dict_items([('A', 18), ('B', 20), ('C', 26)])
>>> values = ages.values()
>>> values
dict_values([18, 20, 26])
>>> ages["E"] = 22
>>> len(ages)
4
>>> ages
{'A': 18, 'B': 20, 'C': 26, 'E': 22}
>>> keys
dict_keys(['A', 'B', 'C', 'E'])
>>> values
dict_values([18, 20, 26, 22])
>>> items
dict_items([('A', 18), ('B', 20), ('C', 26), ('E', 22)])
>>> ages.pop("B")
20
>>> ages
{'A': 18, 'C': 26, 'E': 22}
>>> keys
dict_keys(['A', 'C', 'E'])
>>> values
dict_values([18, 26, 22])
>>> items
dict_items([('A', 18), ('C', 26), ('E', 22)])
>>> for key in keys:
... print(key, ages[key])
...
A 18
C 26
E 22
>>> for key, value in items:
... print(key, value)
...
A 18
C 26
E 22