💡大纲

⭕列表、元组、字符串都是序列,列表是可变序列,元组和字符串是不可变序列

一、跟序列相关的操作符

(一)+(拼接)*(重复)

 序列的有关知识-LMLPHP

  • 对于可变序列:列表来说,在对其进行重复操作后,id值不变
  • 对于不可变序列:元组、字符串来说,重复操作后id值会变化,因为不能对其本身进行直接操作,是创建了一个新的变量

(二)同一性运算符:is is not

序列的有关知识-LMLPHP

(三)包含问题:in not in 

序列的有关知识-LMLPHP

(四)删除一个或多个指定对象:del

序列的有关知识-LMLPHP

 序列的有关知识-LMLPHP

二、跟序列相关的函数

(一)列表、元组、字符串相互转换

1、可迭代对象转换为列表

list("fishc") # ['f', 'i', 's', 'h', 'c']
list((1,2,3,4,5)) # [1, 2, 3, 4, 5]

2、可迭代对象转换为元组

tuple("fishc") # ('f', 'i', 's', 'h', 'c')
tuple([1,2,3,4,5]) # (1, 2, 3, 4, 5)

3、可迭代对象转换为字符串

age = 24
print("My age is "+str(age))    # My age is 24

(二)min() max()

s = [1,1,2,3,5]
min(s) 

x = "fishc"
min(x) # 'c'

序列的有关知识-LMLPHP

(三)len() sum() 

序列的有关知识-LMLPHP

(四)sorted() reversed()

list1 = [2, 5, 2, 8, 19, 3, 7]
list2 = sorted(list1)
print(list1) # [2, 5, 2, 8, 19, 3, 7]
print(list2) # [2, 2, 3, 5, 7, 8, 19]
sorted(list1, reverse = True) # [19, 8, 7, 5, 3, 2, 2] 降序
t = ["Apple","Banana","Fishc","Pen","Book"]
sorted(t) # ['Apple', 'Banana', 'Book', 'Fishc', 'Pen']
sorted(t,key=len) # ['Pen', 'Book', 'Apple', 'Fishc', 'Banana']
s = [1,2,5,8,0]
reversed(s) # 一个迭代器<list_reverseiterator at 0x1f27215f5b0>
list(reversed(s)) # [0, 8, 5, 2, 1]

(五)all() any()

1、any()

👉有一个为真就返回True

2、all()

👉全真,则返回True

print(any([False,1,0,None]))   
print(all([False,1,0,None]))

(六)enumerate()

seasons = ["Spring","Sunmmer","Fall","Winter"]
enumerate(seasons) # <enumerate at 0x1f27255f650>
list(enumerate(seasons)) # [(0, 'Spring'), (1, 'Sunmmer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons,10)) # [(10, 'Spring'), (11, 'Sunmmer'), (12, 'Fall'), (13, 'Winter')]

(七)zip()

x = [1,2,3]
y = [4,5,6]
zipped = zip(x,y)
list(zipped) # [(1, 4), (2, 5), (3, 6)]
tuple(zipped) # ((1, 4), (2, 5), (3, 6))
str(zipped) # '<zip object at 0x000001F271EB33C0>'

序列的有关知识-LMLPHP

(八)map()

mapped = map(ord,"FishC")
list(mapped) # [70, 105, 115, 104, 67]
mapped = map(pow,[2,3,10],[5,2,3])
list(mapped) # [32, 9, 1000]
list(map(max,[1,2,5],[2,2,2],[0,3,9,8])) # [2, 3, 9] 第三个参数的8是没有可比较的对象的

(九)filter() 过滤器

list(filter(str.islower,"FishC")) # ['i', 's', 'h']

三、迭代器 vs 可迭代对象

(一)iter() 

x = [1,2,3,4,5]
y = iter(x) # y成为一个迭代器
type(x) # list
type(y) # list_iterator 列表迭代器

(二)next() 

next(y) # 1
next(y)
next(y)
next(y)
next(y) # 5
next(y) # 在将迭代器都输出结束后,会输出一个异常
z = iter(x)
next(z,"没啦")
next(z,"没啦")
next(z,"没啦")
next(z,"没啦")
next(z,"没啦")
next(z,"没啦") # 输出结束后会抛出给定的内容
06-11 19:44