标签:创建 枚举 字符 list type abc object iter enum
1.列表、元组和字符串的共同点
2.创建序列
>>> list(‘abcdefg‘) [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] >>> list([1,2,3,4,5]) [1, 2, 3, 4, 5] >>> list((‘a‘,1,5,8,9,6)) [‘a‘, 1, 5, 8, 9, 6] >>>
3.重要方法
len
>>> len((‘a‘,1,5,8,9,6)) 6 >>>
max,min
>>> a = (‘a‘,1,5,8,9,6) >>> b = (‘3‘,1,5,8,9,6) >>> max(a) Traceback (most recent call last): File "<pyshell#85>", line 1, in <module> max(a) TypeError: ‘>‘ not supported between instances of ‘int‘ and ‘str‘ >>> max(b) Traceback (most recent call last): File "<pyshell#86>", line 1, in <module> max(b) TypeError: ‘>‘ not supported between instances of ‘int‘ and ‘str‘ >>> b = (3,1,5,8,9,6) >>> max(b) 9 >>>
可以看出在使用max的参数必须是数据类型一致的序列
sum
>>> sum(b) 32
>>> b = (3,1,5,8,9,6) >>> sum(b,1) 33
sorted
>>> b = (3,1,5,8,9,6) >>> sum(b,1) 33 >>> sorted(b) [1, 3, 5, 6, 8, 9] >>>
reversed
>>> numbers = [1,2,5,6,8,3,8,4] >>> reversed(numbers) <list_reverseiterator object at 0x000001EA6BA17C18> >>>
这样调用是直接返回一个list对象,所以需要用list解析
<list_reverseiterator object at 0x000001EA6BA17C18> >>> list(reversed(numbers)) [4, 8, 3, 8, 6, 5, 2, 1] >>>
enumerate 枚举
>>> enumerate(numbers) <enumerate object at 0x000001EA6BA326C0> >>> list(enumerate(numbers)) [(0, 1), (1, 2), (2, 5), (3, 6), (4, 8), (5, 3), (6, 8), (7, 4)] >>>
enumerate返回的也是list对象,所以list解析,最终返回一个包含第一个值为索引,第二个值为值的多个元组的列表
zip
>>> a = [1,2,3,4,5,6,7,8] >>> b = [5,6,5,4] >>> zip(a,b) <zip object at 0x000001EA6BAB76C8> >>> list(zip(a,b)) [(1, 5), (2, 6), (3, 5), (4, 4)]
类似男女成对,女生数量不够就会生出很多单身狗^_^
标签:创建 枚举 字符 list type abc object iter enum
原文地址:https://www.cnblogs.com/xiangdongsheng/p/13415324.html