python语法基础知识第四关第二题_python 任何基础知识,包括语法等

*)根据结果返回True或者False的返回语句可以这样写:

if md5.hexdigest()==db[user]:

return True

else:

return False

#改为 return md5.hexdigest()==db[user]

*)python字符串倒置的几个方法

*)isinstance( )

>>> help(isinstance)

Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)

Return whether an object is an instance of a class or of a subclass thereof.

A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to

check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)

or ...`` etc.

#例子

>>> isinstance(2,(int,float))#检查2是否为 int或者float类型

True

*)pass语句

*)math.exp(X)返回结果是e^x

>>> math.exp(100)

2.6881171418161356e+43

>>> pow(math.e,100)

2.6881171418161212e+43

*)input

input(prompt=None, /)

从标准输入中读取字符串,并且删去尾随的换行符

prompt 字符串如果存在,将会在要读取的输入前被标准化输出,并且不带尾随的换行符

*)if语句有个特点,他是从上到下判读,如果某个分支的条件为True,那么相应的分支执行过后,就忽略掉剩下的elif和else了

*)break和continue的区别:

break:跳出循环,执行for循环下面的语句。

continue:跳出本次循环,执行下次循环。

这两个语句通常都需要if配合使用,需要注意的是,不能滥用break和continue语句,因为会造成代码逻辑分支过多,容易出错,而且continue和break语句能通过改写循环条件或者修改循环逻辑来去掉。

*) 要注意不同函数对全局变量操作时,要确定操作的都是全局变量。或者说是要同步,想让一个变量被另一个只对全局变量处理的函数处理,就要保证他是全局函数

import random

checked=[]

ring_s2e=[]

def find_or_del_ring(ring_start,current_node,find=True):#这个对G操作,其实应该把G传进来的。但我设成了全局变量。那么就要注意这个函数的操作对象时全局变量

abuments=[]

for i in range(len(G)):

if current_node in G[i]:

abuments.append(i)

if not abuments:

return

for node in abuments:

if node in G[ring_start]:

if find:

ring_s2e.append('环:%d-%d'%(ring_start,node))

else:

G[ring_start].remove(node)

elif "%d-%d"%(ring_start,node) not in checked:

checked.append("%d-%d"%(ring_start,node))

find_or_del_ring(G,ring_start,node,find)

def creat_DAG(node_size=10):

--snip--

result=[]

for i in range(node_size):

find_or_del_ring(i,i,False)#问题出在这里了,这个函数是在find_or_del_ring()处理后,将reslut赋值给G的,但忘了find__()方法的操作对象是全局G,等于说这里调用方法起不到作用,但我没有想到这些。

--snip--

def check_if_DAG(G):

for i in range(len(G)):

find_or_del_ring(i,i,True)

--snip--

def print_line(para,prefix=''):

--snip--

G=[]

if __name__ == "__main__":

G=creat_DAG(10)

checked=[]

check_if_DAG(G)

*)return 可当作函数的退出语句

*)tuple 单元素的写法

a=(1,)#这是正确的单元素的写法

#如果不加逗号,就和数学小括号混淆了

*)if __name__=="__main__":中定义的也是全局变量

def test():

print(global_variable)

if __name__=="__main__":

global_variable=111

test()

#输出:111

*)2e3

#不导入numpy也是可以这样用的

>>> import numpy as np

>>> print(+2e3)

2000.0

>>> print(+2e4)

20000.0

>>>

*)lambda表达式

flage=[False for i in range(len(algorithm_list))]

if (reduce(lambda x,y:x and y,flage)):

应用:

*)lambda还可以当作函数对象储存

>>> a.append(lambda x:x*5)

>>> a

[5, 5, 5, at 0x000001776C874BF8>]

>>>

1)在map、reduce、filter、sorted中

2)在闭包中

def get_y(a,b):

return lambda x:ax+b

y1 = get_y(1,1)

y1(1) # 结果为2

#常规函数

def get_y(a,b):

def func(x):

return ax+b

return func

y1 = get_y(1,1)

y1(1) # 结果为2

Python之禅中有这么一句话:Explicit is better than implicit(明了胜于晦涩),就是说那种方式更清晰就用哪一种方式,不要盲目的都使用lambda表达式。

*)缩进的坏处就是“复制-粘贴”功能失效了,这是最坑爹的地方。当你重构代码时,粘贴过去的代码必须重新检查缩进是否正确。此外,IDE很难像格式化Java代码那样格式化Python代码。

*)可以这样写

time_template='time=%ds'

#使用

time_text.set_text(time_template%frameno)

*)向字典dict中添加键值对直接写就好了

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8 # 更新

dict['School'] = "RUNOOB" # 添加

*)for 循环中不要写return语句

*)for 循环中使用递归通过return 会让for 循环不能彻底执行(for 循环能被return终止)

def find_ring(current_node,ring_terminal):

abutment=[]#存放current_node的邻接点

for abutment_list_index in range(len(G)):

if current_node in G[abutment_list_index]:

abutment.append(abutment_list_index)

if not abutment:

# checked.append('%d-%d'%(current_node,ring_terminal))

return 0

for i in abutment:

if '%d-%d'%(i,ring_terminal) in checked:

continue

elif i in G[ring_terminal]:

ring_s2e.append('环%d--%d'%(i,ring_terminal))

continue

else:

checked.append('%d-%d'%(current_node,ring_terminal))

#return find_ring(i,ring_terminal)#假如for循环第一遍是进入这个递归,执行一次就会退出for 你信不信,因为for循环能被retrun终止

find_ring(i,ring_terminal)#应该这样

*)在定义函数的参数时,如果定义了默认参数(默认参数可以位置参数的形式写),则在调用的时候,”位置参数“必须出现在关键字参数之前:

#定义:

def creat_data(type='random',data_start=-1000,data_end=1000,size=1000):

----snip----

#调用:

collection=creat_data('random',-1000,1000,size=1000)#正确的调用

collection=creat_data(type='random',-1000,1000,size=1000)#错误的调用

*)写桶排序的过程中遇到一个很有意思的事情,在为元素分桶的时候,没有考虑负数,根据商向下取整的原理将分桶代码写为:

bucket_count=(max_value-min_value)//default_bucket_size+1

bucket[i//(default_bucket_size+1)]=insertion2bucket(bucket[i//(default_bucket_size+1)],i)

正数分时没问题,但遇到负数时会出现:

>>> -88//5

-18

原以为这样会造成溢出,最后运行了一遍发现并没有:

未排序之前: [-449, 875, 554, 999, 322, -903, 756, -766, 270, -189]

排序后:[270, 322, 554, 756, 875, 999, -903, -766, -449, -189]

只是出现了先有正数,后有负数的情况,这让我想到了list[-1]是取最后一位,那么在上面的代码中,为负值的话是从后面开始数。正好跟上面的结果相吻合

*)为方法添加提示即选中方法的时候旁边有提示:如(方法必须写在

if __name__=='__main__': 外面

1248430-20190712111123956-1583251590.png

需要在定义方法的时候使用多行注释添加语句

1248430-20190712111219719-548312267.png

*)删除列表中多个元素,连续的:

>>> del(a[0])

>>> a

[2, 3, 4, 5]

>>> del(a[2:])

>>> a

[2, 3]

>>>

*)元组中的值不可以单个修改

参考链接:https://www.cnblogs.com/duwenxing/p/7348561.html

*)num(list)可以求和

*)还可以这样用列表给多个用户赋值

a, b, c, d, e, f, g, h = range(8)

*)对错误没有思考,误解了错误,并且没有验证

bucket[(10-(collection[j]//i)%10)%10].append(collection[j])#最后又%10是避免出现-20%10=10的情况

*)重复使用的变量应该在使用后及时初始化,特别是结合循环的时候

# bucket=[[] for i in range(10)]#重复使用的变量应该清空

--snip--

for i in divisor:

bucket=[[] for i in range(10)]#应该放在循环里

*)请谨记除非if中有return等中断的语句,否则请务必加else流程

if collection[j]//i>0:#这样切割数据

bucket[(collection[j]//i)%10].append(collection[j])#考虑余数,直接将余数当成下标

#否则就说明已经完成了#这里就忘记加else了,导致下面这里每次都执行

completed.append(collection.pop(j))

*)遍历一维数组和二维数组的混合数组

for i in a:

... if type(i)==type(a):

... b.extend(i)

... else:

... b.append(i)

*)可以这样制造特定元素个数的空数组

>>> a=[None for i in range(5)]

>>> a

[None, None, None, None, None]

>>> a[0].append(5)

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'NoneType' object has no attribute 'append'

>>> a=[[] for i in range(5)]

>>> a

[[], [], [], [], []]

>>>

*)python中没有null 只有None,None就是null的意思

*)一种转换数据类型的方式

difference.append(float('%.6f'%(time1-time2)))

*)使用for in 遍历列表,列表中的元素将会是str(错误的,是因为格式化时没写正确,正确的写法已经修改为)

difference=[]

difference.append(float('%.6f'%(time1-time2)))#正确的是

#这是错误的difference.append('%.6f'%(time1=time2))

for i in difference:

advanceTime+=i

Traceback (most recent call last):

File "some_sort.py", line 675, in

advanceTime+=i

TypeError: unsupported operand type(s) for +=: 'int' and 'str'

*)将一个列表a复制给b,对b进行pop(),a的元素也会少,可以使用deepcopy()来避免

>>> a=[5,6,7]

>>> b=a

>>> b.pop()

7

>>> b

[5, 6]

>>> a

[5, 6]

*)python平方

参考链接:https://blog.csdn.net/islotus/article/details/61858300

>>> pow(2,0)

1

*)python 求log

参考链接:https://www.runoob.com/python/func-number-log.html

>>> math.log(5,2)

2.321928094887362

>>> int(math.log(5,2))

2

>>> math.ceil(math.log(5,2))

3

>>>

*)python保留两位小数

参考链接:https://www.cnblogs.com/Raymon-Geng/p/5784290.html

>>>a = 5.026

>>>round(a,2)

>>> 5.03

>>>float('%.2f' % a)

>>>5.03

*)Python中if 语法糖不能对变量赋值,那样会出错

a,b,c=2,3,4

print('a') if b

#结果

λ python forTest.py

a

a,b,c=2,3,4

a=4 if b

# print(a)

#结果

a=4 if b

^

SyntaxError: can't assign to conditional expression

*)字符串格式化是占位符必须在当前字符串结束之后紧跟

logging.info('--bidirectional_bubble_sort()--message:当前待排序元素:'+' '*40+'length=%d %s'%(length-2*i,collection[i:length-i-1]))

logging.info('--bidirectional_bubble_sort()--message:当前待排序元素:length=%d '+' '*40+'%s'%(length-2*i,collection[i:length-i-1]))

#这个会显示错误:

TypeError: not all arguments converted during string formatting

*)python中 四舍五入 向上取整(注意是向上(坐标轴正方向)或者向下,特别注意ceil(-1.5)为-1)与向下取整

>>> import math

>>> math.ceil(1.1)

2

>>> math.floor(1.1)

1

>>>

*)python中不能这样一起赋值:

i,j=0

i=0,j=0

*)返回参数

def XX():

--snip--

return plt,anim

plt,_=draw_chart(od)#这样接受返回参数

*)copy()和deepcopy()

参考链接:https://blog.csdn.net/qq_32907349/article/details/52190796

*)OPP面向对象编程

*)接受输入input()

>>> print(input('plese enter '))

plese enter 2

2

>>>

*)num[-1]是指最后一位元素

*)Python中函数在代码中的前后顺序并不影响在调用关系:

def test(i,collection):

sum=0

for s in collection:

sum=sum+Multifly(s)#仍然可以调用Multifly

print(i,sum)

def Multifly(num):

*)import 的正确方式:

from matplotlib import animation#正确方式

import matplotlib.animation#错误方式

import matplotlib.animation as ani#可能正确,因为plt就是这样的

#使用

anim=animation.FuncAnimation(fig,animate,frames=200,interval=60,blit=True)

*)关于可变参数使用

def modify(*password1,id,name,email):#想让password1变成可变参数,参考https://www.liaoxuefeng.com/wiki/1016959663602400/1017261630425888里“如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:”

# check_admin(request)

logging.info('*'*30+'id参数为'+id)

logging.info('*'*30+'name参数为'+name)

logging.info('*'*30+'email参数为'+email)

logging.info('*'*30+'password参数为'+password1)

#结果

INFO:root:使用这些参数调用: {'id': '001556249218238f1b1ed77562c4add92ba541eaabd1edb000', 'name': '我是管理员', 'email': '11111@qq.com'}

INFO:root:******************************id参数为001556249218238f1b1ed77562c4add92ba541eaabd1edb000

INFO:root:******************************name参数为我是管理员

INFO:root:******************************email参数为11111@qq.com

INFO:root:******************************password参数为()

#必须要改成这样

def modify(*,password1,id,name,email):

这个问题从修改密码开始,当我点击重置密码后,使用重置的密码却登录不上去,一开始我在后台比较登录和修改时的加密逻辑,甚至到了把登录里的加密逻辑放到修改模块里的地步,尽管他们看起来一模一样,最后我终于确认了不是逻辑的问题,我就觉得可能是参数的问题,其实这时候我应该去比较登录和修改里的参数的,但是我没有,我直接用上面的输出来进行验证,最后终于发现了是参数类型的顺序写错了,虽然这个问题解决了,但是又引出了新的问题,到底应该怎样拼写不同类型参数的顺序呢?

*)进入其他盘的命令

#不是这样

C:\Users\Administrator.SC-201605202132

λ cd D:

D:\cmder\vendor\git-for-windows

#是这样

C:\Users\Administrator.SC-201605202132

λ D:

D:\cmder\vendor\git-for-windows

λ

*)python 数组(没有总结完全)

参考链接:https://www.cnblogs.com/ifantastic/p/3811145.html

python中的数组名也是指向数组存放的地址

a=[1,2,4]

b=a

#我们并没有复制a所指引的列表。我们只是创建了一个新的标签b,然后将其指向a所指向的列表。

内建函数id()可以返回对象的唯一id。该id是对象的内存地址。

>>> a = [1, 2, 3]>>> b =a>>> a.append(4)>>> printa

[1, 2, 3, 4]>>> printb

[1, 2, 3, 4]

这样复制

new = old[:]#表示切片

b = a[:]

#切片

*)在函数中使用全局变量

参考链接:https://www.cnblogs.com/phoebus0501/archive/2011/01/18/1938728.html

先在函数中用global声明一下就可以了,不需要也不能(?)用一次声明一次

全局变量不需要在方法外先声明

def test():

global AAAA#注意这一句,并且全局变量一般都为大写

AAAA=2

return

def test2():

global AAAA#别的函数中使用也必须先声明

AAAA=3

if __name__=='__main__':

test()

test2()

print(AAAA)

def model_choose(str,model):

#jieba_cut=functools.partial(jieba.cut,cut_all=True)

global result #使用result

if model==1:#标志着是全模式

result.append('全模式')#不能将行代码包括下面的都写成global result...

jieba.cut(str,cut_all=True)

elif model==2:#标志着精确模式

result.append('精确模式')

return jieba.cut(str,cut_all=False)

else:#搜索硬性模式

result.append('搜索引擎模式')

return jieba.cut_for_search(str)

str ='可以使用类似今天看那个偏函数'

model=2

result=[]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值