列表
[ ]
括起來,[]
是一個空列表,不包含任何值,相似於空字符串,負數下標表示從後邊開始,-1
表示列表最後一個下標,它是一種可變的數據類型,值能夠添加、刪除或改變;+
用於鏈接兩個列表並獲得一個新列表;*
用於一個列表和一個整數,實現列表的複製;del
將刪除列表中下標處的值;in
、not in
用於肯定一個值是否在列表中;cat = ['fat', 'black', 'loud'] size, color, disposition = cat
sort()
方法對列表中排序時需注意的3件事:
sort()
方法當場對列表排序;sort()
和sorted()
方法的比較:sort(key = None, reverse = False)
就地改變列表,sorted(iterable, key = None, reverse = False)
返回新的列表,對全部可迭代對象均有效;supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] supplies.sort() print(supplies) supplies = ['pens', 'staplers', 'flame-throwers', 'binders'] sortedSupplies = sorted(supplies) print(supplies) print(sortedSupplies)
\
:續行字符;( )
,和字符串同樣是不可變的,值不能被修改、添加或刪除;list()
將元組轉換爲序列,tuple()
將序列轉換爲元組;#序列轉元組 pets = ['K', 'M', 'N'] print(tuple(pets)) #元組轉序列 pets = ('K', 'M', 'N') print(list(pets))
>>> spam = [0, 1, 2, 4, 5] >>> chees = spam >>> cheese[1] = 'Hello' >>> spam [0, 'Hello', 2, 4, 5] >>> cheese [0, 'Hello', 2, 4, 5]
copy()
和deepcopy()
:處理列表或序列時,若不但願改動影響原來的列表或字典,則使用copy()
函數,如果要複製的列表中包含了列表,則使用deepcopy()
代替;字典和結構化數據
{key:value}
;keys()
、values()
、items()
:分別對應於字典的鍵、值和鍵-值對;get(要取得其值的鍵, 鍵不存在時返回的備用值)
:>>> picnicItems = {'apples':5, 'cpus':2} >>> 'I am bringing ' + str(picnicItems.get('cups', 0) + ' cups.' I am bringing 2 cups. >>> 'I an bringing ' + str(picnicItems.get('eggs', 0) + ' cups.' I am bringing 0 eggs.
setdefault(要檢查的鍵, 檢查的鍵不存在時設置的值)
:第一次調用以後即存在,再次調用不會改變第一次賦給的鍵值;>>> spam = {'name':'Pooka', 'age':5} >>> spam.setdefault('color', 'black') 'black' >>> spam {'color':'black', 'age':5, 'name':'Pooka'} >>> spam.setdefault('color', 'white') 'black' >>> spam {'color':'black', 'age':5, 'name':'Pooka'}
集合:無序、不重複的數據組合,主要做用爲:python
格式輸出:pprint()
和pformat()
;app
import pprint info = {'name':'K', 'age': 23} pprint.pprint(info) #下列這句和上句結果相同 #print(pprint.pformat(info))
#嵌套的字典和列表 allGuests = {'Alice':{'apple':4, 'pretzels':19}, 'Bob':{'apple':3, 'sandwiches':4}, 'Carol':{'cups':5, 'apple pies':4}} def totalBrought(guests, item): numberBrought = 0; for k, v in guests.items(): numberBrought += v.get(item, 0) return numberBrought print('Apple = ' + str(totalBrought(allGuests, 'apple')))
字符串操做
\
;r
,原始字符串徹底忽略全部的轉義字符,打印出字符串中全部的倒斜槓;>>> print(r'That is Carol\'s cat.') That is Carol\'s cat.
>>> print('''Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob''') Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob
ljust()
,右對齊rjust()
,居中center()
;pyperclip
模塊中的copy()
和paste()
函數;