1. 程式人生 > >[Python] Python 學習記錄

[Python] Python 學習記錄

mat 否則 C# 報錯 python 重復字符串 內存 pytho 官方網站

1.概論

弱類型 一個變量能被賦值時能與原類型不同

x = 1

x = "1" #不加分號,給x賦值為int後再次賦值為string是可行的

與或非 and or not

/ #除法的結果是浮點數, 9 / 3 = 3.0

// #結果是整數 10 // 3 = 3

空值為None(相當於null)

內置類型 Numbers(整數和浮點數), Strings,Lists

print(‘‘)

print("%%") #% 字符串打印單引號和雙引號皆可

print(r‘C:\Users\local‘) #C:\User\local raw 表示不轉義 相當於C#中@

字符串跨多行

print(‘‘‘ 內容

內容‘‘‘)

‘‘‘內容‘‘‘

2.字符串

字符編碼

ASCII 使用一個字節 包含127個編碼 (大小寫英文、數字、特殊符號)

Unicode 使用兩個字節表示一個字符 (偏僻的使用4個字節)

Utf-8(8-bit Unicode Transformation Format) 針對Unicode的可變長編碼

屬於ASCII的字符用一個字節,漢字使用兩個字節編碼 完全兼容ASCII

計算機內存中統一使用Unicode編碼,需要保存或傳輸時轉換為Utf-8編碼

ord() #取字符的整數表示

chr() #把編碼轉換為字符

print(‘\u4e2d\u6587‘) #中文

x = b‘ABC‘ #x為bytes 一個字符占用一個字節

x = ‘ABC‘ #x為str

字符串編碼(bytes str互轉)

str->bytes ‘STR‘.encode(‘ascii‘) # utf-8

bytes->str b‘STR‘.decode(‘ascii‘)

字符串格式化

‘%d,%f,%s,%x‘ % (2333,3.14,‘Python str‘,0x23)

‘%2d-%02d‘ %(3,1) #3-01

‘%.2f‘ % 3.1415 #3.14

字符串可以用 + 連接

用 * 用來重復字符串 3 * ‘a‘ #aaa

print(‘a‘ ‘b‘) #ab 這樣a和b會自動連接起來,少寫個 +

word = ‘Python‘

print(word[0]) #p

print(word[-1]) #n 倒數第一個

word[0:2] #Py

word[2:5] #tho

word[:2] #Py

word[4:] #on

word[-2:] #word[-2] + word[-1] on

字符串有不可變性 word[0] = ‘A‘ 會報錯

3.list

x = [1, 2, 3, 4]

和字符串一樣index用起來比較方便

x[0] #1

x[1:2] #[2, 3]

x[-2:] #[3, 4]

y = [4, 5, 6, 7]

x + y #[1, 2, 3, 4, 5, 6, 7] 集合的並操作

tuple

與list類型,但其中的元素不可變

4.分片

有點Matlab的感覺

L = [1,2,3]

L[0:2] L[0] L[1]

L[1:] #L[1] 到最後一個元素 或者寫成L[1:-1]

L[-1] 最後一個元素

L[:10:2] #前10個數,每兩個取一個 [0,2,4,6,8]

5.map() & reduce()

map(func, [1,2,3])

將[1,2,3]中每個元素作為參數執行一次func

reduce(func, [1,2,3])

func(func(1,2),3)

練習解答

輸入:[‘adam‘, ‘LISA‘, ‘barT‘],輸出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]

 def normalize(name):
     first = name[0].upper()
     for i in name[1:]:
             first = first + i.lower()
     return first

L1 = [adam, LISA, barT]
L2 = list(map(normalize, L1))
print(L2)

6. filter()

filter(func,[1,2,3,4])

和map類似,以每個元素為參數調用func,返回為ture的保留,否則丟棄

sorted([2,3,4,5,6,7],key = comparer, reverse = false)

傳一個比較方法即可快速實現排序

參考鏈接

字符串和編碼-廖雪峰的官方網站

https://docs.python.org/3/tutorial/introduction.html

[Python] Python 學習記錄