# 在 Python 中获取数组的子数组

Vaibhav Vaibhav 2022年12月21日

## 在 Python 中使用切片获取数组的子数组

``````object[start:end:step]
``````

• `object` - 一个列表或一个字符串。
• `start` - 切片的起始索引。默认值为 `0`
• `end` - 切片的结束索引。请注意，作为此索引的值不是最终结果的一部分。默认值是可迭代对象的长度。
• `step` - 最终结果中每个索引之间的增量数。默认情况下，它是 `1`

``````array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = array[1:4]
b = array[0:8]
c = array[6:]
d = array[:5]
print(a)
print(b)
print(c)
print(d)
``````

``````[2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
[7, 8, 9, 10]
[1, 2, 3, 4, 5]
``````

``````a = ["Hello", "World", "Computer", "Science", "GitHub", "StakeOverflow"]
b = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1.1, 2.2, 3.3, 4.4, 5.5],
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
["Q", "W", "E", "R", "T", "Y"],
[True, False, None, None, False, True],
]
x = [element[1:5] for element in a]
y = [element[1:3] for element in b]
print(x)
print(y)
``````

``````['ello', 'orld', 'ompu', 'cien', 'itHu', 'take']
[[2, 3], [2.2, 3.3], [0.2, 0.3], ['W', 'E'], [False, None]]
``````

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.