Py.File.Control.Stuff
今日は引き続きPython
ファイル関連は重要なんですが、使ってないとすぐ忘れてしまいます。
#opens file myfile = open('gofuckurself.txt') #reads file - returns entire file - \n等はシカトされる myfile.read() #resets cursor to start of file myfile.seek(0) #outputs list, where each item is a line within the file - \n適応がデリミタ myfile.readlines() #close files after use myfile.close() #closeするのが面倒くさい場合 with open('gofuckurself.txt') as f: #read-write options - where x is 'r','w', etc... with open('gofuckurself.txt', 'x') as f: #w - 既存のファイルがあれば上書きされる、なければ新規で作成される #a - アペンド:既存のファイルに書き足す
次はループ関連・アウトプットのコントロール
# controlling list outputs list = ['go', 'fuck', 'ur$self'] for x in list: print(x,end=' ') Output = go fuck ur$self # tuple unpacking list_of_tups = [(1,2), (3,4), (5,6)] for n1,n2 in list_of_tups: print(n1) print(n2) Output = 1 2 3 4 5 6 # dict unpacking dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'} for key,value in dict.items(): print(key) print(value) Output = k1 v1 k2 v2 k3 v3 for letter in 'poop': if letter == 'p': continue print(letter, end='') Output = oo print(list(range(0,100,5))) #スライスをリスト化 Output = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] list(enumerate('abcde')) #インデックス追加 Output = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] for index,letter in enumerate('abcde'): print('At index {} the letter is {}'.format(index,letter)) Output = At index 0 the letter is a At index 1 the letter is b At index 2 the letter is c At index 3 the letter is d At index 4 the letter is e #リストのマージ l1 = [1,2,3,4] l2 = ['go','fuck','your','self'] for i in zip(l1,l2): print (i) Output = (1, 'go') (2, 'fuck') (3, 'your') (4, 'self') #リストでの最小・最大 l = [1,2,3,4,5] min(l) max(l) #オブジェクトのエレメントをシャッフル from random import shuffle shuffle(mylist) #ランダムで番号をアウトプット from random import randint randint(0, 100)
イースター何もしなかったなぁ。