python常用類型操作

Numeric Types — int, float, complex

Operation Result
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to floating point
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y

Sequence Types — list, tuple, range

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(x[, i[, j]]) index of the first occurrence of x in s (at or after index i and before index j)
s.count(x) total number of occurrences of x in s

不可變類型

Numbers

# 保留位數 默認0位
round(x[,n])
# 向上進位
math.ceil(x)
# 向下進位
math.floor(x)
# 小數轉分數
2.75.as_integer_ratio()

String

# 首字母大寫
"hello".capitalize()
# 全小寫
casefold()
# 字串數量
str.count(sub[, start[, end]])
# 後綴
str.endswith(suffix[, start[, end]])
#前綴
str.startswith(prefix[, start[, end]])
# 尋找子串,沒找到返回-1
str.find(sub[, start[, end]])
# 格式化
"The sum of 1 + 2 is {0}".format(1+2)
# 檢查是否由字母數字組成
"12345abbb".isalnum() #True
# 檢查是否字母
"12345abbb".isalpha() #True
# 檢查是否數字
"12345".isnumeric() #True
# 拼接一系列字符串
a=["1","2","3","4"]
c="n".join(a) # 1n2n3n4
# 去空格
str.lstrip([chars])
str.rstrip([chars])
str.strip([chars])
# 分割兩部分
c="hello".partition("l")  #('he', 'l', 'lo')
# 分割
'1,2,3'.split(',') # ['1', '2', '3']
# 填充位數
"42".zfill(5) # '00042'

Tuple

#定義
tu=234# list轉tuple
tu = tuple([2,3,4])
# string轉tuple
tu = tuple('string')
# 訪問
tu[0]
# 不可以改變某個元素的值
# 輸出
print(tu)
# 鏈接
tu=(1,2,3)+(4,5,6)
# 複製多份
tu = (1,2,3)*4
# 拆分
tu=(1,2,3)
a,b,c=tu
# 部分拆分
tu=(1,2,3,4,5,6,7,8,9)
a,b,*rest = tu
a,b,*_ = tu #_表示不需要的變量

可變類型

List

a=[1,2,3]
# 複製
b=a.copy() 
print(b) # [1, 2, 3]
# 增加數組
a.extend([3,4])
print(a) # [1, 2, 3, 3, 4]
# 增加元素
a.append(3)
print(a) # [1, 2, 3, 3, 4, 3]
# 某元素個數
print(a.count(2)) # 1
# 某元素第一個下標
print(a.index(2)) # 1
# 排序
a.sort() 
print(a) # [1, 2, 3, 3, 3, 4]
# 在下標2處插入4
a.insert(2, 4)
print(a) # [1, 2, 4, 3, 3, 3, 4]
# 彈出下標爲2的元素
a.pop(2)
print(a) # [1, 2, 3, 3, 3, 4]
# 刪除值爲1的元素
a.remove(1)
print(a) #[2, 3, 3, 3, 4]
# 逆序
a.reverse() # [4, 3, 3, 3, 2]
print(a)
# 清除
a.clear()
print(a) #[]

Set

a={0,1,2,3}
b={2,3,4}
# 添加元素
a.add(5)
print(a) # {0, 1, 2, 3, 5}
# 彈出一個元素
print(a.pop())  # 0
print(a) # {1, 2, 3, 5}
# 刪除一個元素 必須存在
a.remove(5)
print(a) # {1, 2, 3}
# a.remove(6)  #KeyError
# 刪除一個元素 不用必須存在
# a.discard(6) # do nothing
# a-b
c = a.difference(b)
print(c) # {1}
# a-b並更新a
a.difference_update(b)
print(a) # {1}
# a與b的交集
c = a.intersection(b) 
print(c) # set()
# 將a更新爲 a與b的交集
a.intersection_update(b) 
print(a) # set()
# a,b交集是否爲空
print(a.isdisjoint(b)) # True
# a是否是b的子集
print(a.issubset(b)) # True
# a是否包含b
print(a.issuperset(b)) # False
# 只在a中或只在b中的元素
c=a.symmetric_difference(b)
print(c) # {2, 3, 4}
# 將a更新爲只在a中或只在b中的元素
a.symmetric_difference_update(b)
print(a) # {2, 3, 4}
# a,b並集
c=a.union(b)
print(c) # {2, 3, 4}
# 將a更新爲a,b並集
a.update(b)
print(a) # {2, 3, 4}

Dictionary

a = {'a': 1, 'b': 2, 'c': 3}
b = {'x': 1, 'y': 2, 'c': 4}
# 更新字典 key不能重複
a.update(b)
print(a) # {'a': 1, 'b': 2, 'c': 4, 'x': 1, 'y': 2}
# 彈出對應key
a.pop('x')
print(a) # {'a': 1, 'b': 2, 'c': 4, 'y': 2}
# 返回key值列表
print(a.keys()) # dict_keys(['a', 'b', 'c', 'y'])
# 返回value列表
print(a.values()) #dict_values([1, 2, 4, 2])
# 遍歷
for k, v in a.items():
    print(k, v)
'''
a 1
b 2
c 4
y 2
'''
# 獲取對應key的值
print(a.get('b')) # 2
# 彈出一對key value
k, v = a.popitem()
print(k, v) # y 2
print(a) # {'a': 1, 'b': 2, 'c': 4}
# 查詢 k 如果查到返回對應value,未查到就返回設定的默認值
a.setdefault('k', 0)
print(a['k']) # 0
print(a) # {'a': 1, 'b': 2, 'c': 4, 'k': 0}
a.setdefault('k', 10)
print(a['k']) # 0
print(a) # {'a': 1, 'b': 2, 'c': 4, 'k': 0}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章