Python序列操作举例

# 序列操作举例
# 序列包括字符串、列表和元组
import itertools

listed = [1, 2, 3]
listed *= 2
print(listed)  # [1, 2, 3, 1, 2, 3]
print(id(listed))  # 2062263906432 对象的id,唯一

# 对象是否相等
x = "hello"
y = "hello"
print(x is y)  # True
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y)  # False

# 是否包含、是否不包含
print("he" in "hello")  # True
print("a" in ["a", "b"])  # True
print("a" not in ["a", "b"])  # False

# 删除对象
x = [1, 2, 3]
del x[0]
print(x)  # [2, 3]
del x  # 删除对象,该对象就不存在了

x = [1, 2, 3, 4, 5]
# 最小值
print(min(x))  # 1
# 最大值
print(max(x))  # 5
# 累加
print(sum(x))  # 15
print(sum(x, start=100))  # 115 指定初始值

# 获取序列长度,超长会报错
print(len(x))  # 5

# 排序
x = [3, 2, 1, 5, 4]
print(sorted(x))  # [1, 2, 3, 4, 5]  排序,生成新的列表,不修改原列表
x.sort()  # 排序,改变原列表
print(x)  # [1, 2, 3, 4, 5]
print(sorted(x, reverse=True))  # [5, 4, 3, 2, 1] 倒序排列,不修改原列表
x.reverse()  # 倒序排列,改变原列表
print(x)  # [5, 4, 3, 2, 1]
print(sorted("bacd"))  # ['a', 'b', 'c', 'd']

# zip 缝合列表
x = [1, 2, 3]
y = [1, 2, 3]
ziped = zip(x, y)
print(list(ziped))  # [(1, 1), (2, 2), (3, 3)]
z = "hello"
print(list(zip(x, y, z)))  # [(1, 1, 'h'), (2, 2, 'e'), (3, 3, 'l')]
print(list(
    itertools.zip_longest(x, y, z)))  # [(1, 1, 'h'), (2, 2, 'e'), (3, 3, 'l'), (None, None, 'l'), (None, None, 'o')]

# map 依次处理序列
mapped = map(ord, "hello")
print(list(mapped))  # [104, 101, 108, 108, 111]
mapped = map(pow, [2, 3, 4], [1, 2, 3])
print(list(mapped))  # [2, 9, 64]

# filter 根据判断条件过滤序列
my_filter = filter(str.islower, "Hello")
print(list(my_filter))  # ['e', 'l', 'l', 'o']

 

posted @ 2023-01-10 03:26  星瑞  阅读(48)  评论(0编辑  收藏  举报