常用的輸入方式
s = input() # 會輸入一行,讀進來 a 是一個字串。
a = int(s) #s 轉換為整數
a = int(input()) # 將輸入的字串轉換為整數,整數才能加減乘除
n = int(input('please input n:')) # 可以輸出一段訊息再讀入
所以其實 input() 是一個函數,他會回傳輸入的一行文字。
如何在同一行輸入兩個整數(空白間格):
a,b = map(int, input().split())
input().split() 的作用:將 input()字串以空白間格切斷成多個字串。試試
a,b = "foo bar".split()
map() 的作用:map(某函數名, 一些東西,可能是個 list) 把這些東西一一丟進該函數運作。
在一行輸入三個整數的方法:
a,b,c = map(int, input().split())
.split() (翻譯:分開)
a,b = "foo bar".split() # 變成 ["foo", "bar"]
print(a,b) # foo bar
c,d = "Aa,Bb".split(",")
print(c,d) # Aa Bb
map()
map(某函數名, 一些東西) 把這些東西一一丟進該函數運作。
nums = ["1", "2", "3"]
result = map(int, nums)
這時 result = [ int("1"), int("2"), int("3") ]
nums = ["1", "2", "3"]
a, b, c = map(int, nums)
print(a, b, c) # 1 2 3
簡單介紹 list
a = [1, 5, 4, 3, 7, 2, 4, 1]
print(a) # python 井字號之後該行是註解,註解是給人看的,編譯器不看
print(*a) # 這個先記一下,相當是 C 語言的指標
print(*a, sep=',') # 分隔符號可以更改
注意!假設 a、b 是 list, a = b 是製作別名,不是複製。
要複製要用:
a = b.copy() # b.copy() 回傳 b 的內容
list 常用函數
最大、最小、總和
a = [5, 3, 4]
large = max(a)
small = min(a)
middle = sum(a) – large - small
排序
a = [3, 1, 5, 7, 3, 4, 2, 5]
a.sort()
print(a) # [1,2,3,3,4,5,5,7]
如果要由大而小排序呢?可以這樣下指令
a.sort(reverse=True)