0%

Python易筋经-拾遗

“为学日益,为道日损。
损之又损,以至于无为。
无为而无不为。
取天下常以无事,及其有事,不足以取天下。”1

列表

字符串索引分片

格式:[lower:upper:step]
[lower,upper)

列表与整数相乘

1
l  = [3,5,'gradient','dropout','l2']
2
l * 2

output:

1
[3, 5, 'gradient', 'dropout', 'l2', 3, 5, 'gradient', 'dropout', 'l2']

列表可以通过索引和分片进行修改

1
l[0] = ['deep learning']
2
l

output:

1
[['deep learning'], 5, 'gradient', 'dropout', 'l2']
1
l[0:2] = ['DeepLearning','regularizatioin']
2
l

output:

1
['DeepLearning', 'regularizatioin', 'gradient', 'dropout', 'l2']

列表中某个元素出现的次数

1
l2 = ["DeepLearning",'normalization']
2
l + l2
3
l3 = l + l2
4
l3

output:

1
['DeepLearning',
2
 'regularizatioin',
3
 'gradient',
4
 'dropout',
5
 'l2',
6
 'DeepLearning',
7
 'normalization']
1
l3.count('DeepLearning')

output:

1
2

元组

跟列表类似,但不可变,且有序。

(12,) #定义单个元素的元组。

1
a = (12,)
2
print a
3
print type(a)

output:

1
(10,)
2
<type 'tuple'>
1
a = (12)
2
print type(a)

output:

1
<type 'int'>

将列表转换为元组

1
tuple(l)

output:

1
('DeepLearning', 'regularizatioin', 'gradient', 'dropout', 'l2')

不可变集合

frozenset

1
flight_distance = {}
2
city_pair = frozenset(['Los Angeles', 'New York'])
3
flight_distance[city_pair] = 2498
4
flight_distance[frozenset(['Austin', 'Los Angeles'])] = 1233
5
flight_distance[frozenset(['Austin', 'New York'])] = 1515
6
flight_distance

output:

1
{frozenset({'Austin', 'New York'}): 1515,
2
 frozenset({'Austin', 'Los Angeles'}): 1233,
3
 frozenset({'Los Angeles', 'New York'}): 2498}

切片

切片的引用机制

1
a = array([0,1,2,3,4])
2
b = a[2:4]

引用机制意味着,Python并没有为 b 分配新的空间来存储它的值,而是让 b 指向了 a 所分配的内存空间,因此,改变 b 会改变 a 的值:

1
b[0] = 10
2
a

output:

1
array([ 0,  1, 10,  3,  4])

可用用.copy()来产生一个复制来避免这种及联修改:

1
b = a[2:4].copy()

花式索引

1
a = array([[ 0, 1, 2, 3, 4, 5],
2
           [10,11,12,13,14,15],
3
           [20,21,22,23,24,25],
4
           [30,31,32,33,34,35],
5
           [40,41,42,43,44,45],
6
           [50,51,52,53,54,55]])
7
a

output:

1
array([[ 0,  1,  2,  3,  4,  5],
2
       [10, 11, 12, 13, 14, 15],
3
       [20, 21, 22, 23, 24, 25],
4
       [30, 31, 32, 33, 34, 35],
5
       [40, 41, 42, 43, 44, 45],
6
       [50, 51, 52, 53, 54, 55]])

对于二维花式索引,我们需要给定 row 和 col 的值:

1
a[(0,1,2,3,4), (1,2,3,4,5)]
2
output:
3
array([ 1, 12, 23, 34, 45]) #返回的是一条次对角线上的5个值。
1
a[3:, [0,2,5]]
2
output:
3
array([[30, 32, 35],
4
       [40, 42, 45],
5
       [50, 52, 55]]) #返回的是最后三行的第1,3,5列。

与切片不同,花式索引返回的是原对象的一个复制而不是引用。

squeeze 方法除去多余的轴

squeeze 返回一个将所有长度为1的维度去除的新数组。

1 :老子《道德经》第四十八章,老子故里,中国鹿邑。