我们把 列表、字符串、元组统称为 序列。他们有很多相似点,
下面介绍几个类方法:
①list方法--创建列表
>>> list("fuck you") #字符串创建列表['f', 'u', 'c', 'k', ' ', 'y', 'o', 'u']
>>> list((1,2,4,5,36,7,8,99)) #将元组的元素放进列表
[1, 2, 4, 5, 36, 7, 8, 99]
②tuple()将可迭代的对象转换为元组
>>> tuple("fuck you")
('f', 'u', 'c', 'k', ' ', 'y', 'o', 'u')
>>> tuple(['a','b','c'])
('a', 'b', 'c')
③str(obj)将obj对象转化为字符串
>>> str(float(32*5)+int(32.5))
'192.0'
④len()
6
⑤max()
>>> max([1,2,3,4,5,6,7,8,99])99
>>> max((1,2,9,"wo")) #在使用max和min方法时,序列中必须是同类型的元素。
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'
⑥min()
>>> list1 = [3,3,45,67,89]
>>> min(list1)
3
⑦sum(),直接sum(list1+list2)会出错
>>> list3 = list1 + lsit2
>>> sum(list3)
369.769
>>> sum(list3,1) 带参数的会加上参数位置的数
370.769
⑧sorted()
>>> sorted(list3)
[3, 3, 45, 49.569, 56.3, 56.9, 67, 89]
⑨reversed() 倒序方法,直接调用返回对象,类方法调用可以返回序列
>>> list(reversed(list3))
[49.569, 56.9, 56.3, 89, 67, 45, 3, 3]
⑩enumerate(),枚举方法,给每一个元素贴标签号码
>>> list(enumerate(list3))
[(0, 3), (1, 3), (2, 45), (3, 67), (4, 89), (5, 56.3), (6, 56.9), (7, 49.569)]
list类方法生成的是一个list,调用enumerate方法得到的内部为 元组
11 zip()打包方法,成双成对,杀死单身狗你的方法
(非常尴尬,我不知道怎么打带括号的11...)
>>> a = ['a','v','p','o','r','n']
>>> man = a
>>> women = [6,2,3,5,7]
>>> list(zip(man,women))
[('a', 6), ('v', 2), ('p', 3), ('o', 5), ('r', 7)]
同学们可以发现,zip方法是把两个列表的内容成双成对的放到了一起,元组的形式,多的man列表元素直接干掉了...男同胞们得努力。