【Python数据分析基础-6】数据结构之序列函数
0. 引入
上篇文章介绍了列表及其相关方法,这篇文章介绍一下列表以及其他序列的函数。
1. 排序(sort、sotred)
1.1 sort
列表有个专门的排序方法:sort,该方法不需要新建对象!
a = [4, 5, 3, 6, 8, 9, 1]
a.sort()
a
[1, 3, 4, 5, 6, 8, 9]
再来看看元素是字符串的列表排序:
s = ['tu', 'dou', 'tong', 'xue']
s.sort()
s
['dou', 'tong', 'tu', 'xue'] # 按照字母顺序进行排序
如果想要按照字符串长度进行排序,可以传入参数
s = ['tu', 'dou', 'tong', 'xue']
s.sort(key=len)
s
['tu', 'dou', 'xue', 'tong']
1.2 sorted
除此之外,序列包括列表都可以使用sorted函数返回一个新建的已排序列表。该函数不仅适用于列表适用于元组等其他序列,但是返回的是列表!
a = [4, 5, 3, 6, 8, 9, 1]
sorted(a)
[1, 3, 4, 5, 6, 8, 9]
再来看看当序列为元组时:
b = (2, 5, 3, 7, 5)
print(type(b))
sorted(b)
<class 'tuple'> # b为元组
[2, 3, 5, 5, 7] # 返回了列表
字符串:
s = ['tu', 'dou', 'tong', 'xue']
sorted(s)
['dou', 'tong', 'tu', 'xue']
传入参数:
s = ['tu', 'dou', 'tong', 'xue']
sorted(s, key=len)
['tu', 'dou', 'xue', 'tong']
2. enumerate
enumerate函数用于当我们需要在遍历序列的同时,得到每个元素及其索引。
s = ['tu', 'dou', 'tong', 'xue']
for i, value in enumerate(s): # 索引值赋予i,元素值赋予value
print(i, value)
0 tu
1 dou
2 tong
3 xue
3. zip
zip函数可以将列表、元组或其他序列的元素进行配对,新建一个元组构成的列表:
s1 = ['tu', 'dou', 'tong', 'xue']
s2 = ['jia', 'you']
list(zip(s1, s2))
[('tu', 'jia'), ('dou', 'you')]
zip可以处理任意长度的序列,它生成的列表长度由最短的序列决定。
zip常常和enumerate函数一起使用,并且这其中不需要使用list函数进行转换:
s1 = ['tu', 'dou', 'tong', 'xue']
s2 = ['jia', 'you']
for i, (a, b) in enumerate(zip(s1, s2)):
print(i, (a, b))
0 ('tu', 'jia')
1 ('dou', 'you')
4. reversed
reversed函数可以将序列的元素倒序排列,效果与list[::-1]相同:
a = [4, 5, 3, 6, 8, 9, 1]
print(a[::-1])
list(reversed(a))
[1, 9, 8, 6, 3, 5, 4]
[1, 9, 8, 6, 3, 5, 4]
值得一提的是,reversed是一个生成器,因此需要将其进行实例化(如使用list函数或者进行for循环),否则它是无法直接产生一个倒序的列表。
OK,这篇文章到这里就结束了,下篇文章将介绍字典!