python这15个编程技巧,你需要知道
1 快速交换两个数字次序
>>> x,y=10,20
>>> print(x,y)
10 20
>>> x,y=y,x
>>> print(x,y)
20 10
2 使用三元操作符来实现条件赋值
>>> x=100
>>> y=200 if(x==100) else 300
>>> y
200
3 多行字符串
>>> str="abdbbdbdbdbdd\
dcscevcdvf"
>>> str
'abdbbdbdbdbdddcscevcdvf'
4 存储列表元素到新的变量
>>> A=[3,4,5]
>>> a,b,c=A
>>> a
3
>>> b
4
>>> c
5
5 打印引入模块的绝对路径
>>> import numpy
>>> print(numpy)
<module 'numpy' from 'C:\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\numpy\\__init__.py'>
6 获取python对象具有的方法
>>> A=[1,2,3,4,5]
>>> dir(A)
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
7 使用*运算符解包
A = {'a':1,'b':2,'c':3}
B = [10,20,30]
print(*A)
print(*B)
print(A)
print(B)
-----------
a b c
10 20 30
{'a': 1, 'b': 2, 'c': 3}
[10, 20, 30]
8 找到列表中出现次数最多的数
test = [1,1,1,2,2,2,2,3,3,3,4,4,4,4,4,4,4,5,5,5,5,5,5,5,55]
print(max(set(test), key=test.count))
------------
4
9 重置递归限制
import sys
x = 3000
#python限制递归次数到1000,可以用下面方法重置
print(sys.getrecursionlimit())
sys.setrecursionlimit(x)
print(sys.getrecursionlimit())
-----------
1000
3000
10 检查一个对象的内存使用
import sys
x = 100
print(sys.getsizeof(x))
28
11 从两个相关序列构建一个字典
a = [1, 2, 3]
b = [10, 20, 30]
print(dict(zip(a, b)))
---------------------
{1: 10, 2: 20, 3: 30}
12 用.join()连接字符串
str = ["Hello", "my", "friend"]
str1=" ".join(str)
str2="+".join(str)
print(str1)
print(str2)
-----------
Hello my friend
Hello+my+friend
13 ==和is的区别
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2)
print(list1 is list2)
list3 = list1
print(list3 is list1)
--------------------
True
False
True
14 /和//的区别
>>> print(3/2)
1.5
>>> print(3//2)
1
15 压缩函数
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x, y in zip(list1, list2):
print(x, y)
1 a
2 b
3 c