【Reading Note】Python读书杂记

时间:2022-08-09 16:13:29

赋值

>>> list=[]
>>> app=[list,list,list]
>>> app
[[], [], []]
>>> app[1].append(1)
>>> app
[[1], [1], [1]]
>>> id(app[1])
1666670423944
>>> id(app[2])
1666670423944

条件语句:

>>> app=[1,'',"cat",[]]
>>> for i in app:
	print(app[i])
>>> for i in app:
	print(i)

1

cat
[]
>>> for i in app:
	if i:
		print(i)

1
cat
>>> [i for i in app]
[1, '', 'cat', []]
>>> [i for i in app if i]
[1, 'cat']

any和all

>>> any(w!=0 for w in app)
True
>>> all(w!='' for w in app)
False

元组:

>>> t='ass',33,''
>>> t
('ass', 33, '')

各种遍历序列的方式

>>> s
(2, 5, 3, 1, 6, 7, 95, 3)
>>> [n for n in s]
[2, 5, 3, 1, 6, 7, 95, 3]
>>> [n for n in sorted(s)]
[1, 2, 3, 3, 5, 6, 7, 95]
>>> [n for n in set(s)]
[1, 2, 3, 5, 6, 7, 95]
>>> [n for n in reversed(s)]
[3, 95, 7, 6, 1, 3, 5, 2]
>>> [n for n in s[::-1]]
[3, 95, 7, 6, 1, 3, 5, 2]
>>> [n for n in set(s).difference(t)]
[1, 2, 3, 5, 6, 7, 95]
>>> t=[1,23,4,5]
>>> [n for n in set(s).difference(t)]
[2, 3, 6, 7, 95]
>>> [n for n in random.shuffle(s)]

训练集和测试集语料划分:9:1

>>> text=open(r"C:\Users\BNC-PC\Desktop\text.txt","r").read()
>>> len(text)
34176
>>> cut=int(0.9*len(text))
>>> training_data,test_data=text[:cut],text[cut:]
>>> len(training_data)
30758
>>> len(test_data)
3418
>>> text == training_data + test_data
True
>>> len(training_data)/len(test_data)
8.998829724985372
>>> 

合并

>>> words='我 是 中国 人 , 我 爱 祖国'.split()
>>> worelen=[w for w in words]
>>> worelen
['我', '是', '中国', '人', ',', '我', '爱', '祖国']
>>> '='.join(w for w in worelen)
'我=是=中国=人=,=我=爱=祖国'

函数:

def bncsum(m,n):
    sum=0
    if n:
        sum=m/n
    else:
        sum=n
    print(sum)


>>> bncsum(4,5)
0.8
>>> bncsum(4,0)
0
>>> help(bncsum)
Help on function bncsum in module __main__:

bncsum(m, n)