物件操作
List
#Insert
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print "Final List : ", aList
#Reverse
aList.reverse()
#去除重複
newList = list(set(aList))
# 刪除
li = [1,2,3,4,5,6]
# 删除對應索引的元素
del li[2]
# li = [1,2,4,5,6]
# 删除最后一个元素
li.pop()
# li = [1,2,4,5]
# 刪除list中指定位址的內容並指定到新的變數中
a = li.pop(0)
# li = [2,4,5]
# 删除指定值的元素
li.remove(4)
# li = [2,5]
參考連結: https://www.tutorialspoint.com/python/list_insert.htm https://www.douban.com/note/277146395/
判斷a list內容是否都出現在b list中: http://thispointer.com/python-check-if-a-list-contains-all-the-elements-of-another-list/
排序
x = [1,5,2,3,4]
x.reverse() # 大到小
x.sort() # 小到大
a = sorted(x) # 保留原始,並產生小到大
參考連結: http://www.iplaypy.com/jinjie/jj114.html
Dict
遍歷
列出所字典內容,.keys()、.values()、dict.keys()、.items()
# python
x = {1:1, 0:0, 2:2}
# 列出所有key
print(x.keys())
# 列出所有key的list
print(list(x.keys))
# 同時提取key與value
for key, value in x.items():
print(key, value)
刪除
指定key並刪除
# python3
x = {1:1, 0:0, 2:2}
x.pop(1)
print(x)
# {0: 0, 2: 2}
y = {1:1, 0:0, 2:2}
del y[1]
print(y)
# {0: 0, 2: 2}
# 兩種方式皆可用
# 更新key (0 ==> 1)
y[1] = y.pop(0)
# {2: 2, 1: 0}
參考資料: https://blog.csdn.net/mmc2015/article/details/50777349
排序
result = sorted(dict1.items(), key=lambda d: d[1]) # 回傳list,裡面是turple
https://segmentfault.com/a/1190000004959880
判斷
判斷型態
if isinstance(number, int):
print('ok')
判斷數字 http://www.runoob.com/python/att-string-isdigit.html http://www.runoob.com/python3/python3-string-isnumeric.html
判斷數字
raw = "345"
raw.isnumeric() # true/false
https://www.itread01.com/article/1533266784.html
https://blog.mimvp.com/article/25955.html
is vs ==
is是相同物件
==是相同值
http://www.iplaypy.com/jinjie/is.html
http://blog.blackwhite.tw/2013/05/python-is.html
Class
https://marco79423.net/articles/淺談-python-的屬性/
https://medium.com/@weilihmen/關於python的類別-class-基本篇-5468812c58f2
Copy
# python3
import copy
a = {'a': 1}
b = copy.deepcopy(a) # 複製新的物件
http://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
sort
http://blog.51cto.com/wangwei007/1100742
string insert方式
s[:4] + '-' + s[4:]
https://stackoverflow.com/questions/5254445/add-string-in-a-certain-position-in-python
Last updated
Was this helpful?