在 Python 中常用的序列是列表(List)和元组(Tuple),列表(List)是 Python 的主力序列;这两者的区别:列表(List)是可修改的,元组(Tuple)是不可修改的。Python中的序列是很强大的,可以进行切片(本方只介绍简单切片)、相加、相乘等操作。

序列切片

切片(slicing):访问特定范围内的元素
切片格式:list[开始索引(包括):结束索引(不包括)]
索引可以是正索引或负索引,负索引从最后以 -1 开始往前标识

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
numbers_slicing = numbers[3:5]
print(numbers_slicing) # [4, 5]

numbers_slicing = numbers[:3] # 开始索引默认为0
print(numbers_slicing) # [1, 2, 3]

numbers_slicing = numbers[3:] # 结束索引默认为最后一个索引
print(numbers_slicing) # [4, 5, 6, 7, 8, 9, 10]

numbers_slicing = numbers[:-3] # -3 为倒数的第三个索引
print(numbers_slicing) # [1, 2, 3, 4, 5, 6, 7]

序列相加

numbers1 = [1, 2, 3, 4]
numbers2 = [5, 6, 7]
numbers = numbers1 + numbers2
print(numbers) # [1, 2, 3, 4, 5, 6, 7]

numbers1 = [1, 2, 3, 4]
string = ['hello', 'world']
listall = numbers1 + string
print(listall) # [1, 2, 3, 4, 'hello', 'world']

序列相乘

string = 'python' * 10
print(string) # pythonpythonpythonpythonpythonpythonpythonpythonpythonpython

numbers = [1, 2] * 3
print(numbers) # [1, 2, 1, 2, 1, 2]

# None、空列表和初始化
sequence = [None] * 10
print(sequence) # [None, None, None, None, None, None, None, None, None, None]

成员资格 - 判断元素在列表中是否存在

list1 = ['hello', 'python']
if 'python3.7' not in list1:
    print('list1 元素中不存在 `python3.7`') 

if 'python' in list1:
    print('list1 元素中存在 `python`') 

序列的遍历

array = ['hi', 'python', 2020]
for item in array:
    print(item)
'''
hi
python
2020
'''

# 带索引遍历
for index, item in enumerate(array):
    print(index, item)
'''
0 hi
1 python
2 2020
'''

本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论