【Effective Python】5-Pythonic-了解切割序列的办法

5-Pythonic-了解切割序列的办法

Python 提供了一种把序列切成小块的方法。
针对内置的 list、str 和 bytes 的切割。

5.1 切割序列

  • 一个列表
list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
#  index =  0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#  index = -0(-10),-9,-8,-7,-6,-5,-4,-3,-2,-1 
  • 正常的切割序列 [start_index:end_index]
print(list_num[:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print(list_num[1:4])
# index-123 [2, 3, 4]

print(list_num[2:])
# index-2... [3, 4, 5, 6, 7, 8, 9, 0]

print(list_num[:8])
# index-...7 [1, 2, 3, 4, 5, 6, 7, 8]

print(list_num[7:2])
# if start_index > end_index []
  • 负值切割
print(list_num[-4:-2])
# index~-4,-3 [7, 8]
print(list_num[-4:])
# index~-4... [7, 8, 9, 0]

print(list_num[-0:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(list_num[-12:])
# print all [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print(list_num[-1:0])
# if start_index > end_index []
print(list_num[-1:-1])
# []

print(list_num[-1:])
# [0]
print(list_num[-12:6])
# [1, 2, 3, 4, 5, 6]

5.2 传值

  • 对于元组而言,传值纬度 必须保持一致。
c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
c1, c2 = c[2:4]
print(c1, c2)
# 3 4

c3, c4 = c[5:8]
print(c3, c4)
# ValueError: too many values to unpack (expected 2)
  • 不同于元组,列表的切片不考虑纬度,可以伸缩。
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

a[2:4] = ['a', 'b', 'c', 'd']
print(a)
# index_start: 2 扩张
# [1, 2, 'a', 'b', 'c', 'd', 5, 6, 7, 8, 9, 0]

b =  [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b[2:7] = ['123','456']
print(b)
# index_start: 2 缩减
# [1, 2, '123', '456', 8, 9, 0]

你可能感兴趣的:(Effective,Python)