Python入门——Day4(序列)

序列

序列是python的基本数据结构,可以分类:可变序列 list,不可变序列tuple,str。
序列有列表list,元组tuple,字符串str的共同特点。

  • 可以通过索引得到每一个元素
  • 默认所引值从0开始
  • 可以利用切片得到一个范围内元素的集合
  • 有很多共同的操作符(重复,拼接,成员关系)

list() -> new empty list
list(iterable) 迭代器,重复过程,反馈结果的活动

max = tuple[0]

for each in tuple1:
	if each > max:
		max = each

return max

序列常用操作

>>> a = list()
>>> a
[]  #空序列
>>> b = 'I love you!'
>>> b = list(b)
>>> b
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'y', 'o', 'u', '!']
>>> c = (1,2,3,4,5,6,7)
>>> c = list(c)
>>> c
[1, 2, 3, 4, 5, 6, 7]
>>> len(a) #求长度
0
>>> len(b)
11
>>> max(c)#求最大值
7
>>> max(b)#返回序列中最大的ASCII码值
'y'
>>> tuple1 = (1,2,3,4,5,6,7,8,9,0)
>>> max(tuple1)
9
>>> numbers = (1,34,63,76,107,-93,-68)
>>> min(numbers)
-93

需要注意的,当列表中含有字符,数字,等不同的数据类型时,max(),min()等函数不能使用。

>>> numbers = [1,34,63,76,107,-93,-68]
>>> numbers.append('a')
>>> numbers
[1, 34, 63, 76, 107, -93, -68, 'a']
>>> max(numbers)
#报错:
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    max(numbers)
TypeError: '>' not supported between instances of 'str' and 'int'

>>> numbers = [1,34,63,76,107,-93,-68]
>>> sum(numbers)#求和
120
>>> sum(numbers,9)
129
>>> sorted(numbers)#排序
[-93, -68, 1, 34, 63, 76, 107]
#序列反向输出
>>> list(reversed(numbers))
[-68, -93, 107, 76, 63, 34, 1]
#按照索引对序列每个元素编码
>>> list(enumerate(numbers))
[(0, 1), (1, 34), (2, 63), (3, 76), (4, 107), (5, -93), (6, -68)]
#打包
>>> a = [1,2,3,4,5,6,7]
>>> b = [9,8,7,6,5]
>>> zip(a,b) #需要把zip转化为list才能输出
<zip object at 0x000001CD0B563400>
>>> list(zip(a,b))
[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
>>> list(zip(b,a))
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5)]
发布了12 篇原创文章 · 获赞 13 · 访问量 305

猜你喜欢

转载自blog.csdn.net/weixin_45253216/article/details/104521915
今日推荐