注:不定期持续更新
1. 基本函数
1.1 format
方法
1.1.1 基本操作
>>>'{} {}'.format('hello', 'world')
'hello world'
>>>'{0} {1}'.format('hello', 'world')
'hello world'
>>>'{1} {0} {1}'.format('hello', 'world')
'world hello world'
1.1.2 设置参数
## 方法1
>>>'国家:{country}, 首都:{capital}'.format(country='Byzantium', capital='Constantinople')
'国家:Byzantium, 首都:Constantinople'
## 方法2
>>>dic = {'country': 'Byzantium', 'capital': 'Constantinople'}
>>>'国家:{country}, 首都:{capital}'.format(**dic)
'国家:Byzantium, 首都:Constantinople'
## 方法3
>>>list = ['Byzantium', 'Constantinople']
>>>'国家:{0[0]}, 首都:{0[1]}'.format(list)
1.1.3 格式化数字
- 保留小数点后两位
>>>'{:.2f}'.format(3.1415926)
3.14
- 带符号保留小数点后两位
>>>'{:+.2f}'.format(3.1415926)
+3.14
- 数字补=,填充左边,宽度为4
>>>'{:=>4}'.format(2)
===2
- 数字补-,填充右边,宽度为5
>>>'{:-<5}'.format(3)
3----
- 以逗号分隔的数字形式
>>>'{:.}'.format(10000)
10,000
- 百分比格式
>>>'{:.1%}'.format(0.3927)
39.3%
- 指数格式
>>>'{:.3e}'.format(123456789)
1.235e+08
- 右对齐
>>>'{:>10}'.format(13456)
13456
- 左对齐
>>>'{:<10}'.format(13456)
13456
- 居中对齐
>>>'{:^10}'.format(1345)
1345
2. Numpy库
clip()
使得一个数组中的数值保持在一个区间内,区间外的数值被剪切至区间上下限
>>>x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0])
>>>np.clip(x,2,5)
array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2])
extract()
在特定条件下从一个数组中提取特定元素
>>>array = np.random.randint(20, size=12)
>>>array
array([13, 1, 0, 10, 6, 18, 12, 13, 18, 17, 14, 12])
>>>cond = np.mod(array, 2) == 1
>>>cond
array([ True, True, False, False, False, False, False, True, False,
True, False, False])
>>>np.extract(cond, array)
array([13, 1, 13, 17])
>>>np.extract(((array < 3)|(array > 15)), array)
array([ 1, 0, 18, 18, 17])
where()
用于从一个数组中返回满足特定条件的元素,不提供参数时,默认返回满足特定条件的元素的索引位置
注:在依据某个条件对数据进行转换时特别好用,不用写循环什么的
>>>y = np.array([1,5,6,8,1,7,3,6,9])
>>>np.where(y>5)
(array([2, 3, 5, 7, 8], dtype=int64),)
>>>np.where(y>5, "Hit", "Miss")
array(['Miss', 'Miss', 'Hit', 'Hit', 'Miss', 'Hit', 'Miss', 'Hit', 'Hit'],
dtype='<U4')
3. Pandas库
4. Random库
random.seed()
:初始化随机数生成器random.randint(a, b)
:在a与b之间返回随机整数,范围包含a与brandom.choice(seq)
:从非空序列seq中返回一个随机元素random.shuffle(x)
:将序列x随机打乱位置random.sample(population, k)
:返回从总体序列或集合中选择的唯一元素的 k 长度列表,用于无重复的随机抽样random.random()
:返回 [0.0, 1.0) 范围内的下一个随机浮点数random.uniform(a, b)
:返回一个随机浮点数 Nrandom.guass(mu, sigma)
:高斯分布random.normalvariate(mu, sigma)
:正态分布random.gammavariate(alpha, beta)
:Gamma分布random.betavariate(alpha, beta)
:Beta分布
5. 一些小技巧
- 例如将
a = [1, 2, 3]
与b = ['1', '2', '3']
相互转换,可以使用b = map(int, a)
或者b = [int(x) for x in a]
,不过好像用map还是更好一些。 - 如果要将一个字符串翻转,可以使用例如
'abcd'[::-1]
或者''.join(reversed('abcd'))