a = 2
a = a + 1
b = 2
import
來加入的函數和變數等等。a = 2
print(id(a))
b = 2
print(id(b))
基本操作:
x in seq
x not in seq
a + b # a, b要是同一種sequence
a * n #repeat n times
seq[i]
seq[i:j] # 拿出第i到第j-1個
seq[i:j:k] # 從第i~第j中,每k個拿出一個
len(seq), max(seq), min(seq)
seq.index(x)
seq.count(x)
marvel_hero = ["Steve Rogers", "Tony Stark", "Thor Odinson"]
print(type(marvel_hero), marvel_hero)
marvel_hero.append("Hulk")
marvel_hero.insert(2, "Bruce Banner") # insert "Bruce Banner" into index 2
print(marvel_hero)
print(marvel_hero.pop()) # default: pop last item
marvel_hero[0] = "Captain America"
print(marvel_hero[1:-1])
%timeit list_hero = [i.lower() if i.startswith('T') else i.upper() for i in marvel_hero]
print(list_hero)
%%timeit
list_hero = []
for i in marvel_hero:
if i.startswith('T'):
list_hero.append(i.lower())
else:
list_hero.append(i.upper())
print(list_hero)
marvel_hero.sort(reverse=False) # sort in-place
marvel_hero
list_hero_sorted = sorted(list_hero) # return a sorted list
print(list_hero_sorted)
a = [1, 2, 3, 4, 5]
b = a
print(id(a), id(b), id(a) == id(b))
b[0] = 8888
print(a)
tuples = item1, item2, item3, ...
例如:
def f(a, b=0):
return a1*a2 + b
f((87, 2)) # return 87*2 + 0
love_iron = ("Iron Man", 3000)
cap = "Captain America",
print(type(love_iron), love_iron)
print(love_iron + cap)
print("Does {} in the \"love_iron\" tuples?: {}".format("Iron", 'Iron' in love_iron))
print("Length of cap: {}".format(len(cap)))
max(love_iron)
enumerate()
用在for-loop裡面可以依次輸出(i, 第i個項目),這樣就不用另外去記錄你跑到第幾個項目for e in enumerate(love_iron + cap):
print(e, type(e))
range(start, stop[, step])
even_number = [x for x in range(0, 30, 2)]
for i in range(2, 10, 2):
print("The {}th even number is {}".format(i, even_number[i-1]))
hero_id = {"Steve Rogers": 1,
"Tony Stark": 666,
"Thor Odinson": 999
}
hero_code = dict(zip(hero_id.keys(), ["Captain America", "God of Thunder", "Iron Man"]))
print(type(hero_code), hero_code)
# dict[key]: 輸出相對應的value,如果key not in dict則輸出 KeyError
# dict.get(key, default=None): 輸出相對應的value,如果key not in dict則輸出default
hero_name = "Steve Rogers"
print("The codename of hero_id {} is {}".format(hero_id.get(hero_name), hero_code[hero_name]))
hero_id.update({"Bruce Banner": 87})
print(hero_id)
注意!輸出的順序不一定代表加入dictionary的順序! 但是key和value的對應順序會一樣。
print(hero_id.keys())
print(hero_id.values())
print(hero_id.items())
for name, code in hero_code.items():
print("{} is {}".format(name, code))
set_example = {"o", 7, 7, 7, 7, 7, 7, 7}
print(type(set_example), set_example)
A = set("Shin Shin ba fei jai")
B = set("Ni may yo may may")
print(A)
print(B)
A ^ B
a = set([[1],2,3,3,3,3])
a
# 安裝它只要一個步驟:
pip3 install numpy
import numpy as np
b = np.array([[1,2,3],[4,5,6]]) # 2D array
print(b)
print(b.shape, b.dtype)
print(b[0, 0], b[0, 1], b[1, 0]) # array[row_index, col_index]
z = np.zeros((8,7))
z
1:5
的語法。yeee = np.fromfile(join("data", "numpy_sample.txt"), sep=' ')
yeee = yeee.reshape((4,4))
print(yeee)
print(yeee[:2,0]) # 取出第一個column的前兩個row
print(yeee[-1,:]) # 取出最後一個row
yeee[yeee > 6]
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
print(x.dot(y) == np.dot(x, y))
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v
print(y) # v 分別加在x的每一個row
x[:]
拿出的東西是x的一個View,也就是說,看到的其實是x的data,更動View就是更動x。.copy()
。x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
shallow = x[:]
deep = x.copy()
shallow[0, 0] = 9487
deep[0, 0] = 5566
print(x)
Access mode | access_flag | detail |
---|---|---|
Read only | r | 從檔案開頭讀取 |
Write only | w | 寫進去的東西會從頭開始寫,如果本來有內容,會覆蓋過去 |
Append only | a | 寫進去的東西會接在檔案後面 |
Enhance | + | 讀+寫或是讀+append |
f = open(filepath, access_flag)
f.close()
from os.path import join
with open(join("data", "heyhey.txt"), 'r', encoding='utf-8') as f:
print(f.read() + '\n')
print(f.readlines())
f.seek(0) # 回到檔案開頭
readlines = f.readlines(1)
print(readlines, type(readlines)) # 以 '\n'為界線,一行一行讀
single_line = f.readline()
print(single_line, type(single_line)) # 一次只讀一行
print()
# 也可以放進for-loop 一行一行讀
for i, line in enumerate(f):
print("Line: {}: {}".format(i, line))
break
with open(join("data", "test.txt"), 'w+', encoding='utf-8') as f:
f.write("Shin Shin ba fei jai")
f.seek(0)
print(f.read())