无名 发表于 2022-5-8 16:03:07

【SOS】实用的Python小技巧(5)(6)(7)(8)(9)

5、使用 hasattr()内置方法获取object属性

1 class SomeClass:
2   def __init__(self):
3   self.attr1 = 10
4   def attrfunction(self):
5         print("Attreibute")
6 hasattr(SomeClass, "attrfunction")
7 # Output
8 True

6、使用isinstance()检查变量是否为给定类型

1 isinstance(1, int)
2 #Output
3 True

7、使用map()打印列表中的数字

1 list1 =
2 list(map(print, list1))
3 # Output
4 1
5 2
6 3

一种比循环打印列表内容更快更有效的方法。

8、使用.join()方法格式化datetime日期

1 from datetime import datetime
2 date = datetime.now()
3 print("-".join()
4 # Output
5 '2021-6-15'
9、将两个具有相同规则的列表随机化

1 import numpy as np
2 x = np.arange(100)
3 y = np.arange(100,200,1)
4 idx = np.random.choice(np.arange(len(x)), 5, replace=False)
5 x_sample = x
6 y_sample = y
7 print(x_sample)
8 print(y_sample)
9 # Outputs
10 array()
11 array()
http://cdn.u1.huluxia.com/g4/M01/CF/0C/rBAAdmDKkPWAbWwaAACgxA6ZmZM407.png
页: [1]
查看完整版本: 【SOS】实用的Python小技巧(5)(6)(7)(8)(9)