python 入門學習筆記14

### 列表list ###
 
# 創建一個空list (兩種方法)
empty_list = []
empty_list = list()
 
# 創建一個list
simpsons = ['homer', 'marge', 'bart']
 
# 獲取list元素
simpsons[0] #'homer'
len(simpsons)   # 返回list長度(3)
# 修改list  
simpsons.append('lisa') # ['homer', 'marge', 'bart', 'lisa']
simpsons.extend(['itchy', 'scratchy']) # ['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy']
simpsons.append(['itchy', 'scratchy']) #['homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
simpsons.insert(0, 'maggie') # ['maggie', 'homer', 'marge', 'bart', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
simpsons.remove('bart') # ['maggie', 'homer', 'marge', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
simpsons.pop(0) #['homer', 'marge', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
del simpsons[0]  #['marge', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
simpsons[0] = 'krusty' #['krusty', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy']]
neighbors = simpsons + ['ned', 'rod', 'todd'] #['krusty', 'lisa', 'itchy', 'scratchy', ['itchy', 'scratchy'], 'ned', 'rod', 'todd']
# 在list中查找元素
simpsons.count('lisa')   # 計算元素的個數
simpsons.index('itchy')  # 返回第一元素的索引
# 分割list [開始:結束:跨步]
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
weekdays[0]      # 'mon'
weekdays[0:3]    # 'mon', 'tues', 'wed'
weekdays[:3]     # 'mon', 'tues', 'wed'
weekdays[3:]     # 'thurs', 'fri'
weekdays[-1]     # 'fri' 最後一個元素
weekdays[::2]    # 0,2,4   'mon' 'wed' 'fri'
weekdays[::-1]   # 倒序 (4, 3, 2, 1, 0)  'fri' 'thurs' 'wed' 'tues' 'mon'
 
#倒序
list(reversed(weekdays))
 
# 在原地排序
simpsons.sort()
simpsons.sort(reverse=True)  # 倒序
simpsons.sort(key=len)       # 通過key排序
 
 
# 返回一個排過序的列表(不修改原始列表)
sorted(simpsons)
sorted(simpsons, reverse=True)
sorted(simpsons, key=len)
 
# 在排過序的列表中插入一個元素,並保持排序狀態
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
### 元組(Tuple) ###
# 和list相似,但是它不能改變大小
 
# 創建一個元組
digits = (0, 1, 'two')  # 創建一個元組
digits = tuple([0, 1, 'two'])  # 從list創建元組
zero = (0,)         # 逗號是必不可少的,它指定zero是一個元組,沒有的話就是數字0了
 
# 訪問元組數據
digits[2]   # 返回'two'
len(digits) #      3
digits.count(0)  # 0的個數 (1)
digits.index(1)  # 返回第一個1的索引(1)
 
# 元組裏的元素不能修改
# digits[2] = 2  # 拋出一個錯誤
 
# 拼接元組
digits = digits + (3, 4)
 
# 創建一個重複元素的元組(通常和list一起使用)
(3, 4) * 2   # 返回(3,4,3,4)
 
# 排序一個元組列表
tens = [(20,60), (10, 40), (20, 30)]
sorted(tens)   # 按元組裏的第一個元素排序,第一個元素相同,比較第二個
               # [(10, 40), (20, 30), (20, 60)]
 
# 元組解包
bart = ('male', 10, 'simpson')
(sex, age, surname) = bart   # 一次符三個值
### 字符串 ###

#創建一個字符串
s = str(42)   # 把其它類型的數據轉化爲string
s = 'I like you'
 
# 提取string
s[0]    # 返回 'I'
len(s)  # 返回 10
 
# 分割字符串
s[:6]    # 'I like'
s[7:]    # 'you'
s[-1]    # 'u'
 
# 基本的string方法 (不修改原string)
s.lower()    # 'i like you'
s.upper()    # 'I LIKE YOU'
s.startswith('I')   # True
s.endswith('you')    # True
s.isdigit()         # False (True:數字組成的字符串)
s.find('like')      # 2 索引
s.find('hate')      # -1 沒有找到
s.replace('lkie', 'love')  # 替換 'like' 爲 'love'

# 分割字符串
s.split(' ')  # ['I','like','you']
s.split()     # 同上
s2 = 'a, an, the'
s2.split(',')   # ['a',' an',' the']
 
# 把列表中的字符串連成一個字符串
stooges = ['larry','curly','moe']
' '.join(stooges)     # 'larry curly moe'
 
# 連接字符串
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
s3 + ' ' + str(42) # 'The meaning of life is 42'
 
#移除字符串前後中的空白字符
s5 = '  ham and cheese  '
s5.strip()    # 'ham and cheese'
 
# 字符串替換
'raining %s and %s' % ('cat', 'dogs')    # 老方法
'raining {} and {}'.format('cats', 'dogs') # 新方法
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')
# 字符串格式化
'pi is {:.2f}'.format(3.14159)   # 'pi is 3.14'
###  字典(dictionaries) ###
# 由key-value對組成
# key是唯一的,可以是string,數字,元組
# values 可以是任何值
 
# 創建一個空字典(兩種方法)
empty_dict = {}
empty_dict = dict()
 
# 創建一個字典(兩種方法)
family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)
 
# 把元組列表轉化爲字典
list_of_tuples = [('dad','homer'), ('mom','marge'), ('size', 6)]
family = dict(list_of_tuples)
 
# 獲取字典元素
family['dad']   # 'homer'
len(family)     # 3
family.keys()   # ['dad', 'mom', 'size']
family.values() # ['homer', 'marge', 6]
family.items()  # [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
'mom' in family # True
'marge' in family # False (只判斷key)

# 修改字典
family['cat'] = 'snowball'  # 增加一個新紀錄
family['cat'] = 'snowball ii' # 編輯一個已存在的記錄
del family['cat']         # 刪除一個記錄
family['kids'] = ['bart', 'lisa']  # 值可以是列表
family.pop('dad')          # 刪除一個記錄並返回值
family.update({'baby':'maggie', 'grandpa':'abe'}) # 增加多個記錄
 
family['mom']   # 'marge'
family.get('mom') # 同上
#family['grandma']  # 拋出錯誤
family.get('grandma')  # 返回None
family.get('grandma', 'not found')  # 'not found'
 
family['kids'][0]   # 'bart'
family['kids'].remove('lisa')   # 移除'lisa'
 
# 用字典替換字符串
'youngest child is %(baby)s' % family   # 'youngest child is maggie'
### set  ###
# 無重複集合
 
# 創建空set
empty_set = set()
 
# 創建集合
languages = {'python', 'r', 'java'}
snakes = set(['cobra', 'viper', 'python'])
 
len(languages)  # 3
'python' in languages   # True
 
# set 操作
languages & snakes # 兩個集合的交集  {'python'}
languages | snakes # 聯合   {'cobra', 'r', 'java', 'viper', 'python'}
languages - snakes # {'r', 'java'}
snakes - languages # {'cobra', 'viper'}
 
# 修改集合
languages.add('sql')   # 增加一個元素
languages.add('r')     # 試圖增加一個以存在的元素,忽略,沒有錯誤
languages.remove('java') # 移除一個元素
#languages.remove('c')    # 試圖移除一個不存在的元素,拋出錯誤
languages.discard('c')   # 移除一個存在的元素,如果不存在,忽略
languages.pop()          # 移除並返回元素
languages.clear()        # 清空集合
languages.update('go', 'spark') # 增加多個元素
 
# 排序
sorted(set([9, 0, 2, 1, 0]))  # [0, 1, 2, 9]   去重排序
### 匿名函數(Lambda)###
 
# 普通方式定義函數
def squared(x):
	return x ** 2
 
# lamba
squared = lambda x : x ** 2
 
# 通過最後的字符排列字符串(不用lambda)
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
	return word[-1]
sorted(simpsons, key=last_letter)
# 用lambda
sorted(simpsons, key=lambda word : word[-1])# ['marge', 'homer', 'bart']
### map reduce  filter ###
 
# 'map'把一個操作應用到所有元素上
simpsons = ['homer', 'marge', 'bart']
map(len, simpsons)   # 求每個元素的長度 [5, 5, 4]
map(lambda word: word[-1], simpsons)  # ['r', 'e', 't']
# 等價
[len(word) for word in simpsons]
[word[-1] for word in simpsons]
 
 
# 先把前兩個元素執行某個函數,求的結果,依次計算
reduce(lambda x,y: x + y, range(4)  # (((0+1)+2)+3) = 6
 
# 用指定函數過濾
filter(lambda x: x % 2 == 0, range(5))  # [0, 2, 4]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章