單行輸入
data = map(lambda x:int(x),raw_input().split()) # python2.7
data = list(map(lambda x:int(x),input().split())) # python3
or
import sys
inputs = sys.stdin.readline().strip() # 相當(dāng)于raw_input(), strip() remove last '\n'
指定行數(shù)輸入
n = int(input())
outs = [map(lambda x:int(x),raw_input().split()) for i in range(n)]
多行輸入
sys.stdin相當(dāng)于 while(scanf('%d',&num)!= EOF)
# 計(jì)算輸入序列的總和
import sys
for line in sys.stdin:
line = map(lambda x: int(x),line.split())
print(sum(line[1:]))
輸出字符串的形式
# 對(duì)輸入的字符串序列排序
# 輸入:bb a d
# 輸出:a bb d
import sys
for line in sys.stdin:
line = line.strip().split()
sort_line = sorted(line)
out_line = ' '.join(sort_line)
print(out_line)
關(guān)于數(shù)組的操作
由于在線系統(tǒng)只能用標(biāo)準(zhǔn)庫猴凹,所以用list來表示多維數(shù)組枝缔,假如不使用numpy的話烙样,如何正確切片根悼?
- 判斷l(xiāng)ist是否為空:
any(list) # False if list is empty
any( [ [] ]) # False
any( [] ) # False
- 二維數(shù)組(list)取m-n行折晦,i到j(luò)列
>>> list = [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]]
>>> k = [ tmp[1:3] for tmp in list[:3] ] # 0到2行士败,1到2列
>>> k
[[2, 8], [4, 9], [7, 10]]
list的深復(fù)制
python里對(duì)象的賦值都是進(jìn)行對(duì)象引用(內(nèi)存地址)傳遞
>>> example = ['Happy',23,[ 1,2,3,4]]
>>> tmp = example
>>> id(example)
4432030896
>>> id(tmp)
4432030896 # tmp has same address with example
淺拷貝
淺拷貝會(huì)創(chuàng)建一個(gè)新的對(duì)象
但是控汉,對(duì)于對(duì)象中的元素在抛,淺拷貝就只會(huì)使用原始元素的引用(內(nèi)存地址)
>>> import copy
>>> tmp = copy.copy(example)
>>> id(tmp)
4432361520 # != id(example)
但是钟病,list是可變類型,修改tmp的可變類型還是會(huì)影響example刚梭,不可變類型則不會(huì)肠阱。
>>> tmp[0] = 'Sad' #不可變類型
>>> tmp[-1].append(100) # 可變類型
>>> tmp
['Sad', 23, [1, 2, 3, 4, 100]]
>>> example
['Happy', 23, [1, 2, 3, 4, 100]]
深拷貝
>>> tmp = copy.deepcopy(example)
>>> tmp
['Happy', 23, [1, 2, 3, 4, 100]]
>>> example
['Happy', 23, [1, 2, 3, 4, 100]]
看一看元素的地址
>>> print([id(x) for x in tmp])
[4431963936, 140394571508024, 4432029744]
>>> print([id(x) for x in example])
[4431963936, 140394571508024, 4423907376]
很明顯可變?cè)豯ist的地址發(fā)生了改變。