今天去面试python岗位,碰到一份很有意思的笔试题,里面一堆的平时不怎么注意的细节。在这里分享一下。
我们知道, python round()函数返回浮点数x的四舍五入值。(注意:int是直接取整)
round(70.23456) : 结果 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
但是,有一个坑是这样的:
round(1.5) == 2
round(0.5) == 0
为什么呢? python3中,四舍五入时如果数为 5 ,会保留到偶数的一边
参考:https://www.cnblogs.com/anpengapple/p/6507271.html
众所周知,python语言缩进,是不需要写 “ ; ”的。那分号是干嘛用的?
a = 100;b = 200 # 写在一行,不推荐
# 一行过多不美观,使用 \ 符下一行
b = "aaaaaaaaaaaaaaaaaaaaaaaaaaa" \
"aaaaaaaaaaaaaaaaaaa"
这一点在编程语言里基本都是这样
https://blog.csdn.net/renwotao2009/article/details/51637163
>1.2 - 1.0
0.19999999999999996
>print(1.2-1.0 == 0.2)
False
True 与 1,False 与 0
>True and 1
1 # 为什么不是true?
# 运算时小类型会向大类型转换,bool是int的子类
>True or 1
True
# python 短路逻辑原则
# https://www.cnblogs.com/klvchen/p/8544577.html
>False and 0
False
>False or 0
0
dict
https://www.cnblogs.com/yyds/p/6123917.html
注意:对于dict.keys()、dict.values()和dict.items()这些函数,在Python 2.x中返回的是list对象,而在Python 3.x中返回的是一个叫做字典视图的对象。(for 循环)
映射的底层原理?
地址的区别
>a = [1,2,3]
>b = a[:]
>a == b
True
>a is b
False
>id(a)
2399998401672
>id(b)
2399998333704
如果try里面有return,不会执行else,但仍然执行finally
参考:https://www.cnblogs.com/JohnABC/p/4065437.html
copy:拷贝了引用,并没有拷贝内容
deepcopy: 完全复制
import copy
list1 = [1,2,['a','b'],('c','d')]
list2 = list1
list3 = copy.copy(list1)
list4 = copy.deepcopy(list1)
list1.append(3)
tuple1 = (10,10)
list1[2].append({100})
list1[3] = list1[3] + tuple1
dict1 = {}
dict1['1'] = 1111
#list1[2].append(dict1)
list1[2] += dict1
print(list1)
#(1)结果是: [1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd', 10, 10), 3]
print(list2)
#(2)结果是: [1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd', 10, 10), 3]
print(list3)
#(3)结果是: [1, 2, ['a', 'b', {100}, {'1': 1111}], ('c', 'd')]
print(list4)
#(4)结果是:[1, 2, ['a', 'b'], ('c', 'd')]
参考:https://blog.csdn.net/u012606764/article/details/78398860
_foo __foo __foo__的区别
闭包
def bar(multiple):
def foo(n):
return multiple ** n
return foo
if __name__ == '__main__':
print(bar(2)(3)) # 结果:8
标记数据类型,方便 检查代码
def test(param: int, *args)->str:
# 类型注解不是注释,必须遵守规则
print(param); print(type(args))
new_args = list(args)
b = min(new_args)
a = max(new_args)
print(a+b)
return 'a'
if __name__ == '__main__':
test(1, 2, 3, 4)
a = (1,)
>a = (1,2,3)
>a * 2
(1, 2, 3, 1, 2, 3)
http://www.cnblogs.com/shiqi17/p/9608195.html
def multipliers():
return [lambda x : i*x for i in range(4)]
print [m(2) for m in multipliers()]
output:
# [6, 6, 6, 6]
# 不是[0,2,4,6]
https://download.csdn.net/download/anker_yz/10783538