Home  >  Article  >  Backend Development  >  Python implements the method of naming slices

Python implements the method of naming slices

不言
不言forward
2018-10-15 14:17:532141browse

The content of this article is about the method of naming slices in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Requirements

Our code has become unreadable, with hard-coded slice indexes everywhere, and we want to optimize them.

2. Solution

If there are many hard-coded index values ​​​​in the code, it will lead to poor readability and maintainability.

The built-in slice() function creates a slice object that can be used anywhere where slicing operations are performed.

items=[0,1,2,3,4,5,6]
a=slice(2,4)
print(items[2:4])
print(items[a])

items[a]=[10,11,12,13]
print(items)

del items[a]
print(items[a])
print(items)

Running result:

[2, 3]
[2, 3]
[0, 1, 10, 11, 12, 13, 4, 5, 6]
[12, 13]
[0, 1, 12, 13, 4, 5, 6]

If there is an instance s of the slice object. Information about the object can be obtained through the s.start, s.stop and s.step properties respectively. For example:

items=[0,1,2,3,4,5,6]
a=slice(2,8,3)
print(items[a])
print(a.start)
print(a.stop)
print(a.step)

Result:

[2, 5]
2
8
3

Additionally, slices can be mapped onto sequences of specific sizes by using the indices(size) method. This will return a (start, stop, step) tuple, all values ​​have been properly restricted within the bounds (to avoid IndexError exceptions when doing index operations), for example:

s='HelloWorld'
a=slice(2,5)
print(a.indices(len(s)))
for i in range(*a.indices(len(s))):
    print(str(i)+":"+s[i])

Result:

(2, 5, 1)
2:l
3:l
4:o

The above is the detailed content of Python implements the method of naming slices. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete