刷題筆記——1267.A+B Problem
阿新 • • 發佈:2022-12-06
題目
程式碼
while True:
try:
a,b=map(int,input().strip().split())
print(a+b)
except:
break
筆記
map()函式
語法
map(function, iterable, ...)
,其中 function 是一個函式, iterable 是一個或多個序列。在python2中返回一個列表,而在python3中返回迭代器。
例項
- 使用自定義函式
- 使用lambda匿名函式
a = map(lambdax, y : (x**y,x+y),[2,4,6],[3,2,1]) print(list(a)) # 結果如下 [(8,5),(16,6),(6,7)]
lambdax函式做其他處理
3. 不傳入函式
等同於zip(),將多個列表相同位置的元素歸併到一個元組
a = map(None,[2,4,6],[3,2,1])
print(list(a))
# 結果如下
[(2,3),(4,2),(6,1)]
- 型別轉換
- 元組轉換
a = map(int,(1,2,3))
print(list(a))
# 結果如下:
[1,2,3]
- 字串轉換
map(int,'1234')
print(list(a))
# 結果如下:
[1,2,3,4]
- 提取字典中的key,並將結果放在一個list中
a = map(int,{1:2,2:3,3:4}) print(list(a)) # 結果如下 [1,2,3]
注意
如上文所說,在python3中,使用map得到的返回值是一個迭代器,直接輸出並不能得到結果,將它轉換為list型別後可得目標結果。
strip()方法
語法
str.strip([chars])
, strip() 方法用於移除字串頭尾指定的字元(預設為空格或換行符)或字元序列,並不能刪除中間部分的字元。返回移除之後的新字串。
例項
str = "123abcrunoob321"
print (str.strip( '12' )) # 字元序列為 12
# 結果如下
3abcrunoob3
根據上方例項發現,移除的元素並不受順序影響,只要原字串首尾位置包含字元1和2就會被移除。用一個不同的例項去驗證:
str = "123000abc321000"
print (str.strip( '210' ))
# 結果如下
3000abc3
由此可證實上方論述,同時,如果首尾位置在去除過程中遇到非目標字元,即使該字元後方有目標字元也會停止。