Python slice() 函数用法
2023-09-17 22:29:06
slice()
方法根据指定的范围返回可迭代对象的一部分作为 slice
类的对象。它可以与string、list、tuple、set、字节或range对象一起使用,也可以与实现序列方法__getitem__()
和__len__()
方法custom class对象一起使用。
Syntax:
slice(stop)
slice(start, stop, step)
参数:
- start:(可选)开始迭代对象切片的起始索引。Deault值为none。
- stop:切片应结束的结束索引。
- step:(可选)用于递增起始索引的整数。默认为"无"。
返回值:
返回 slice
类的对象。
下面的示例演示具有字符串值的 slice()
方法。
mystr = 'python114.com'
nums = [1,2,3,4,5,6,7,8,9,10]
portion1 = slice(9)
portion2 = slice(2, 8, 2)
print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])
print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2])
输出:
slice: slice(None, 9, None)
String value: Tutorials
List value: [1,2,3,4,5,6,7,8,9]
slice: slice(2, 8, 2)
String value: tra
List value: [3, 5, 7]
上面,slice(9)
将切片对象作为 slice(None, 9, None)
返回,您可以将其传递给任何可迭代对象以获取该索引部分。
slice()
方法可用于字符串、列表、元组、集合、字节或范围。 下面的示例提取列表对象的部分。
nums = [1,2,3,4,5,6,7,8,9,10]
odd_portion = slice(0, 10, 2)
print(nums[odd_portion])
even_portion = slice(1, 10, 2)
print(nums[even_portion])
输出:
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
使用负索引(Using Negative Index)
slice()
方法还支持负索引。
nums = [1,2,3,4,5,6,7,8,9,10]
even_portion = slice(-9, -1, 2)
print(nums[even_portion])
输出:
[2, 4, 6, 8]
使用索引语法(Using Indexing Syntax)
可以使用iterable_obj[start:stop:step]
快捷语法进行切片,而不是使用 slice()
方法。
nums = [1,2,3,4,5,6,7,8,9,10]
print('Odd nums: ', nums[0:10:2]) # start 0, stop: 10, step:2
print('Even nums: ', nums[1:10:2]) # start 1, stop: 10, step:2
mystr = 'python114.com'
print(mystr[0:9]) # start 0, stop: 9, step:1
print(mystr[9:]) # start 9, stop: end of string, step:1
print(mystr[9::2]) # start 9, stop: end of string, step:2
print(mystr[::2]) # start 0, stop: end of string, step:2
输出:
Odd nums: [1, 3, 5, 7, 9]
Even nums: [2, 4, 6, 8, 10]
Tutorials
Teacher
Tahr
Ttrasece
本文内容总结: