\t製表符>>> print('python')python>>> print("python")python>>> print('\tpython') python\n換行符>>> print("Languages:\nPython\nC\nJavaScript")Languages:Python... ...
\t製表符 >>> print('python') python >>> print("python") python >>> print('\tpython') python \n換行符 >>> print("Languages:\nPython\nC\nJavaScript") Languages: Python C JavaScript >>> print('number:\n1\n2\n3') number: 1 2 3 同時換行、製表,添加空白 >>> print('\n\t1\n\t2\n\t3') 1 2 3 .rstrip()刪除末尾多餘空白,暫時性,永久,賦值到變數中 >>> favorite_language = 'python ' >>> favorite_language 'python ' >>> favorite_language.rstrip() 'python' >>> favorite_language = favorite_language.rstrip() >>> favorite_language File "<stdin>", line 1 favorite_language ^ IndentationError: unexpected indent >>> favorite_language 'python' .rstrip()刪除末尾空白 .lstrip()刪除開頭空白 .strip()刪除兩端空白 >>> number = ' 1 ' >>> number.strip() '1' >>> number.lstrip() '1 ' **乘方 浮點數:帶小數點的數字 str()轉化為字元串 >>> message = 'happy' + age + 'rd birthday!' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> message = "Happy " + str(age) + "rd Birthday!" >>> print(message) Happy 23rd Birthday! 空格,空格,沒有空格就會顯示錯誤 >>> print(1+10) File "<stdin>", line 1 print(1+10) ^ SyntaxError: invalid character in identifier >>> print(1 * 11) 11 在Python中,註釋用井號( #)標識。井號後面的內容都會被Python解釋器忽略,轉行要繼續添加#號,print語句中,沒有被定義的一定要加引號,單引號雙引號都可以 >>> #生日問候 ... print(happy) Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'happy' is not defined >>> # 生日問候 ... print('happy') Tim Peters撰寫的“Python之禪” 列表 索引從 0 而不是 1 開始 >>> bicycles = ['trek', 'cannondale', 'redline', 'specialized'] >>> print(bicycles[0]) trek >>> print(bicycles[2].upper()) REDLINE Python為訪問最後一個列表元素提供了一種特殊語法。通過將索引指定為-1,可讓Python返 回最後一個列表元素。 [-1]返回最後一個列表元素。 >>> bicycles = ['trek', 'cannondale', 'redline', 'specialized'] >>> message = "My first bicycle was a " + bicycles[-1].upper() + '.' >>> print(message) My first bicycle was a SPECIALIZED. 空格是單獨作為一個字元,不要丟 >>> name = ['mike','john','lisa'] >>> message = name[-1].title() + 'is my sex partner.' >>> print(message) Lisais my sex partner. >>> message = name[-1].title() + ' is my sex partner.' >>> print(message) Lisa is my sex partner. 你創建的大多數列表都將是動態的,這意味著列表創建後,將隨著程式的運行增刪元素。例如,你創建一個游戲,要求玩家射殺從天而降的外星人;為此,可在開始時將一些外星人存儲在列表中,然後每當有外星人被射殺時,都將其從列表中刪除,而每次有新的外星人出現在屏幕上時,都將其添加到列表中。在整個游戲運行期間,外星人列表的長度將不斷變化。(要理解這種演算法的思路) 修改列表中第一個元素的值 >>> motorcycles = ['honda', 'yamaha', 'suzuki'] >>> print(motorcycles) ['honda', 'yamaha', 'suzuki'] >>> motorcycles[0] = 'ducati' # 空格會顯示錯誤 File "<stdin>", line 1 motorcycles[0] = 'ducati' ^ IndentationError: unexpected indent >>> motorcycles[0] = 'ducati' #修改列表中第一個元素的值 >>> print(motorcycles) ['ducati', 'yamaha', 'suzuki'] .append()列表末尾添加元素,only one >>> motorcycles = ['honda', 'yamaha', 'suzuki'] >>> print(motorcycles) ['honda', 'yamaha', 'suzuki'] >>> motorcycles.append('ducati') >>> print(motorcycles) ['honda', 'yamaha', 'suzuki', 'ducati'] >>> motorcycles.append('A','B') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: append() takes exactly one argument (2 given) .insert(索引,值) 使用方法insert()可在列表的任何位置添加新元素 從列表中刪除元素 你經常需要從列表中刪除一個或多個元素。例如,玩家將空中的一個外星人射殺後,你很可能要將其從存活的外星人列表中刪除;當用戶在你創建的Web應用中註銷其賬戶時,你需要將該用戶從活躍用戶列表中刪除。你可以根據位置或值來刪除列表中的元素。 使用del語句刪除元素:使用del語句將值從列表中刪除後,你就無法再訪問 motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) del motorcycles[0] print(motorcycles) 使用方法pop()刪除元素:方法pop()(彈出)可刪除列表末尾的元素,並讓你能夠接著使用它 >>> motorcycles = ['honda', 'yamaha', 'suzuki'] >>> print(motorcycles) ['honda', 'yamaha', 'suzuki'] >>> popped_motorcycle = motorcycles.pop() >>> print(motorcycles) ['honda', 'yamaha'] >>> print(popped_motorcycle) suzuki .pop()刪除列表末尾元素,並且可以接著使用該元素 可以使用pop()來刪除列表中任何位置的元素,只需在括弧中指定要刪除的元素的索引即可。 如果你要從列表中刪除一個元素,且不再以任何方式使用它,就使用del語句;如果你要在刪除元素後還能繼續使用它,就使用方法pop()。 不知道要從列表中刪除的值所處的位置。如果你只知道要刪除的元素的值,可使用方法remove()。 使用remove()從列表中刪除元素時,也可接著使用它的值。 motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] print(motorcycles) too_expensive = 'ducati' motorcycles.remove(too_expensive) print(motorcycles) print("\nA " + too_expensive.title() + " is too expensive for me.") .remove()刪除不知道列表中元素位置的值,並且可以繼續使用該值。 方法remove()只刪除第一個指定的值。如果要刪除的值可能在列表中出現多次,就需要 使用迴圈來判斷是否刪除了所有這樣的值。 >>> lisi = ['A','B','C'] >>> list = ['a','b','c','d'] >>> list[0] = 'e' >>> print(list) ['e', 'b', 'c', 'd'] >>> print(list.title()) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'title' >>> list.append(f) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'f' is not defined >>> list.append('f') >>> print(list) ['e', 'b', 'c', 'd', 'f'] >>> del list[-1] >>> print(list) ['e', 'b', 'c', 'd'] >>> list.pop() 'd' >>> print(list) ['e', 'b', 'c'] >>> list.pop(1) 'b' >>> print(list) ['e', 'c'] >>> list = ['a','b','c','d','e','f'] >>> list.remove('a') >>> print(list) ['b', 'c', 'd', 'e', 'f'] >>> list.insert(1,'z') >>> print(list) ['b', 'z', 'c', 'd', 'e', 'f'] 組織列表,排序 使用方法 sort()對列表進行永久性排序 字母順序 cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) 字母順序相反 cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort(reverse=True) print(cars) 1.現在提前假設都是小寫,問題還沒完 >>> cars = ['a','c','b'] >>> cars = cars.sort() >>> print(cars) None >>> cars = ['a','c','b'] >>> cars.sort() >>> print(cars) ['a', 'b', 'c'] >>> cars.sort(reverse = true) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> cars.sort(reverse=true) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> cars.sort(reverse = True) >>> print(cars) ['c', 'b', 'a'] >>> print(cars.title()) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'title' 使用函數 sorted()對列表進行臨時排序 >>> cars = ['bmw', 'audi', 'toyota', 'subaru'] >>> print("Here is the original list:") Here is the original list: >>> print(cars) ['bmw', 'audi', 'toyota', 'subaru'] >>> print(sorted(cars)) ['audi', 'bmw', 'subaru', 'toyota'] >>> print(cars) ['bmw', 'audi', 'toyota', 'subaru'] 要反轉列表元素的排列順序,可使用方法reverse() .reverse()反轉列表元素順序 cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) cars.reverse() print(cars) print(len(cars)) 4 方法reverse()永久性地修改列表元素的排列順序,但可隨時恢復到原來的排列順序,為此 只需對列表再次調用reverse()即可。 使用函數len()可快速獲悉列表的長度,列表中有幾個元素就顯示幾。 操作列表: >>> magicians = ['alice', 'david', 'carolina'] >>> for magician in magicians: ... print(magician) File "<stdin>", line 2 print(magician) ^ IndentationError: expected an indented block >>> magicians = ['alice', 'david', 'carolina'] >>> for magician in magicians: ... print(magician) ... alice david carolina >>> magicians = ['alice', 'david', 'carolina'] >>> for A in magicians: ... print(A) ... alice david carolina 縮進不對不行,for迴圈後面要加冒號,A or magician 是自己命名的,存儲變數用,(這行代碼讓Python從列表magicians中取出一個名字,並將其存儲在變數magician中) for cat in cats: for dog in dogs: for item in list_of_items: 以上操作方式是便於你理解 >>> magicians = ['alice', 'david', 'carolina'] >>> for magician in magicians: ... print(magician.title() + ", that was a great trick!") ... Alice, that was a great trick! David, that was a great trick! Carolina, that was a great trick! 示例二: >>> magicians = ['alice', 'david', 'carolina'] >>> for magician in magicians: ... print(magician.title() + ", that was a great trick!") # 第一次迴圈 ... print("I can't wait to see your next trick, " + magician.title() + ".\n" ) ... Alice, that was a great trick! I can't wait to see your next trick, Alice. David, that was a great trick! I can't wait to see your next trick, David. Carolina, that was a great trick! I can't wait to see your next trick, Carolina. 在for迴圈後面,沒有縮進的代碼都只執行一次,而不會重覆執行。 print("Thank you, everyone. That was a great magic show!") 創建數值列表: Python函數range()讓你能夠輕鬆地生成一系列的數字: range(1,5)函數range()讓Python從你指定的第一個值開始數,併在到達你指定的第二個值後停止,因此輸出不包含第二個值(這裡為5)。 >>> for value in range(1,6): ... print(value) ... 1 2 3 4 5 使用 list()創建數字列表,要創建數字列表,可使用函數list()將range()的結果直接轉換為列表。 >>> numbers = list(range(1,6)) >>> print(numbers) [1, 2, 3, 4, 5] >>> even_numbers = list(range(2,11,2)) >>> print(even_numbers) [2, 4, 6, 8, 10] range(x,y,z) x起始 y停止 z步長(可以不寫) 數range()讓你能夠輕鬆地生成一系列的數字 range(2, 15, 2) >>> for value in range(1,6,2): ... print(value) ... 1 3 5 如何創建一個列表,其中包含前10個整數(即1~10)的平方呢? >>> squares = [] >>> for value in range(1,11): ... square = value**2 ... squares.append(square) ... >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 使代碼簡化 >>> squares = [] >>> for value in range(1,11): ... squares.append(value**2) ... >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 繼續簡化: >>> squares = [value**2 for value in range(1,11)] >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 請註意,這裡的for語句末尾沒有冒號。 要使用這種語法,首先指定一個描述性的列表名,如squares;然後,指定一個左方括弧,並定義一個表達式,用於生成你要存儲到列表中的值。在這個示例中,表達式為value**2,它計算平方值。接下來,編寫一個for迴圈,用於給表達式提供值,再加上右方括弧。 列表名+迴圈 數值計算 >>> digits = list(range(0,10)) >>> print(digits) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> min(digits) 0 >>> max(digits) 9 >>> sum(digits) 45 練習: >>> numbers = list(range(1,21)) >>> print(numbers) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] >>> for value in range(1,21): ... print(value) ... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 >>> numbers = list(range(1,1000001)) >>> min(numbers) 1 >>> max(numbers) 1000000 >>> numbers[0] 1 >>> numbers[-1] 1000000 >>> sum(numbers) 500000500000 >>> numbers = [value**3 for value in range(1,11)] >>> print(numbers) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]