序列类型(列表和元祖包括字符串等)通用的的内建函数

在python中,有许多序列的内建函数,部分函数的使用范围更广,适用于可迭代对象。

一些常见的序列类型的内置函数。

序号

函数     

功能                                      
1 len()  
2 min()、max()  
3 sorted()  
4 reversed()  
5 sum()  
6 enumerate()  
7 zip()  

1.len()对于列表或者元祖来说返回其中元素的个数。对于字符串来说,返回字符串的长度,就是字符串包含的字符个数。

>>> name
['kebi', 'maoxian', 'xiaoniao', 'xinye']
>>> number = (1,3,4,2)
>>> st = 'Hello,World'
>>> len(number)
4
>>> len(name)
4
>>> len(st)   #字符串也是序列的一种特殊情况
11

 2.max():返回列表或者元祖中元素的最大值,对字符串也能操作,但是没什么意义。

    min():返回列表或者元祖中元素的最小值。

 max()和min()在比较取值前都可以指定一个函数作为其元素的处理方法

    关于字符串的顺序可以对照ASCII表来排序。47-57为阿拉伯数字,65到90为大写字母,97到122为小写字母。

>>> number = (1,3,4,2)
>>> name = ['kebi', 'maoxian', 'xiaoniao', 'xinye']
>>> st = 'Hello,World'
>>> max(number)
4
>>> max(name)
'xinye'
>>> max(st)
'r'
>>> ord('W')   #调用ord()函数可以查询字符串的顺序
87
>>> ord('r')
114
>>> min(number)
1
>>> min(name)
'kebi'
>>> min(st)
','
>>> min([-3,6,0,1])
-3
>>> min([-3,6,0,1],key = abs)
0
>>> max((-5,1,4))
4
>>> max((-5,1,4),key = abs)
-5

3.sorted():接受一个可迭代对象作为参数,返回一个有序的列表。

>>> number
(1, 3, 4, 2)              #元祖
>>> st
'Hello,World'             #字符串
>>> s                        
['They', 'stamp', 'them', 'when', 'samll']   #列表

>>> sorted(number)
[1, 2, 3, 4]            #元祖变为列表
>>> sorted(st)             
[',', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']    #字符串变为列表
>>> sorted(s)
['They', 'samll', 'stamp', 'them', 'when']   

有点类似于list()的功能,只是list()不会自动排序

>>> list(st)
['H', 'e', 'l', 'l', 'o', ',', 'W', 'o', 'r', 'l', 'd']

4.reversed():接受一个序列作为参数,返回一个以逆序访问的迭代器。

>>> reversed(number):   #直接访问是不行的
  File "<stdin>", line 1
    reversed(number):
                    ^
SyntaxError: invalid syntax

>>> number
(1, 3, 4, 2)
>>> st
'Hello,World'
>>> s
['They', 'stamp', 'them', 'when', 'samll']

>>> for i in reversed(number):    #作用于元祖
...     print(i)
...
2                         #结果从后往前打印
4
3
1

>>> for i in reversed(st):     #作用于字符串
...     print(i)
...
d
l
r
o
W
,
o
l
l
e
H

>>> for t in reversed(s):    #作用于列表
...     print(t)
...
samll
when
them
stamp
They

5.sum():返回序列和可选数字参数的总和。不是数字不行,数字类型的字符串也不行。

>>> number
(1, 3, 4, 2)
>>> sum(number)
10
>>> sum(number,5)
15

>>> number2 = [1,2,3,4]
>>> stt = '1234'
>>> sum(number2)
10
>>> sum(stt)         #字符串不行
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> s                     #不是数字不行
['They', 'stamp', 'them', 'when', 'samll']
>>> sum(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#还可以添加参数
>>> sum([1,2,3,4],5)
15

6.enumerate():接受一个可迭代对象作为参数,返回一个enumerate对象(同时也是一个迭代器),该对象生成由序列中每个元素的index值和元素值组成的元祖。

               注意:enumerate()的机制和reversed()类似,返回的是一个对象,如果需要显示还要提取。

>>> enumerate(number)
<enumerate object at 0x0000015E5B56E678>  #返回的是一个对象

>>> for i in enumerate(number):
...     print(i)
...
(0, 1)
(1, 3)                  #对字符串、元祖和列表都有用
(2, 4)
(3, 2)

>>> for i in enumerate(st):
...     print(i)
...
(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
(5, ',')
(6, 'W')
(7, 'o')
(8, 'r')
(9, 'l')
(10, 'd')

>>> for i in enumerate(name):
...     print(i)
...
(0, 'kebi')
(1, 'maoxian')
(2, 'xiaoniao')
(3, 'xinye')
>>> for i,sr in enumerate(['kebi','maoxian','xiaoniao']):
...     print(i,sr)                             #多个元素接受
... 
0 kebi
1 maoxian
2 xiaoniao
>>> for i,sr in enumerate(['kebi','maoxian','xiaoniao'],100):#指定其实点
...     print(i,sr)
... 
100 kebi
101 maoxian
102 xiaoniao

 enumerate()还可以指定数字开始的位置

name = ["科比","毛线","小鸟","星爷"]      
print(list(enumerate(name,1)))     #使用list强转

结果:
[(1, '科比'), (2, '毛线'), (3, '小鸟'), (4, '星爷')]

7.zip():以可迭代对象作为参数,返回一个由每个序列的第一个元素组、第二个元素....组成的元祖所组成的列表。只要是可迭代对象都行,列表、元祖、字符串可以混合。

>>> name
['kebi', 'maoxian', 'xiaoniao', 'xinye']
>>> st
'Hello,World'
>>> s
['They', 'stamp', 'them', 'when', 'samll']
>>> number
(1, 3, 4, 2)

>>> zip(name,s)    #返回的是一个对象
<zip object at 0x0000015E5B5734C8>

>>> for i in zip(name,s):        #列表+列表
...     print(i)
...
('kebi', 'They')
('maoxian', 'stamp')
('xiaoniao', 'them')
('xinye', 'when')

>>> for i in zip(s,name):        #以长度最短的一个序列为结束标志
...     print(i)
...
('They', 'kebi')
('stamp', 'maoxian')
('them', 'xiaoniao')
('when', 'xinye')

>>> for i in zip(name,number):    #列表+元祖
...     print(i)
...
('kebi', 1)
('maoxian', 3)
('xiaoniao', 4)
('xinye', 2)

>>> for i in zip(name,st):   #列表+字符串
...     print(i)
...
('kebi', 'H')
('maoxian', 'e')
('xiaoniao', 'l')
('xinye', 'l')

>>> for i in zip(name,number,st):  #多个可以组合
...     print(i)
...
('kebi', 1, 'H')
('maoxian', 3, 'e')
('xiaoniao', 4, 'l')
('xinye', 2, 'l')

8.bytes():

class bytes([source[, encoding[, errors]]])

Return a new “bytes” object, which is an immutable sequence of integers in the range <= 256bytes is an immutable version of bytearray– it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray().

返回值为一个新的不可修改字节数组,每个数字元素都必须在0 - 255范围内,是bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改。

有以下几种情况:

(1)当三个参数都不传的时候,返回长度为0的字节数组。

>>> bytes()
b''

(2)当处理对象为字符串时,encoding参数也必须指定,函数将字符串使用str.encode方法转换成字节数组。

>>> bytes('中文')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding

>>> bytes('中文','utf-8')    #必须指定转码类型
b'xe4xb8xadxe6x96x87'

(3)当处理对象为整数的时候,返回这个整数所指定长度的空字节数组。

>>> bytes(3)
b'x00x00x00'   #返回三个空字节数组
>>> bytes(5)
b'x00x00x00x00x00'
>>> 
>>> bytes(3.2)   #处理的必须是整数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert 'float' object to bytes

(4)当处理对象是一个可迭代对象,那么这个迭代对象的元素都必须符合0<=x<256,以便可以初始化到数组里。

>>> bytes(range(5))
b'x00x01x02x03x04'
>>> bytes([255,2,3,4])
b'xffx02x03x04'
>>> bytes([256,2,3,4])   #可迭代对象必须是0<=x<256之间
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bytes must be in range(0, 256)
>>> bytes(['a','d','rr'])  #字母肯定不行
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

9. memoryview():

返回内存查看对象

>>> ret = bytes([255,2,3,4])    #二进制编码
>>> memoryview(ret)
<memory at 0x7f992b6ec108>
>>> memoryview(ret)[1]
2

10.bytearray():

与bytes()类似,返回一个新的字节数组,但是它可以改变其中的元素,而不改变其id

11.all()和any():判断可迭代对象中是否有空的对象。

>>> all([1,2,3,0])   #all一个为空全为空
False
>>> all([1,2,3])
True
>>> any((1,2,3,0))  #any一个为真全为真
True
>>> any((0,0))
False
原文地址:https://www.cnblogs.com/yangmingxianshen/p/7702886.html