Python for the implementation of slice naming method

  • 2020-12-21 18:05:29
  • OfStack

1, requirements,

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

2. Solutions

Having too many hard-coded index values in your code can lead to poor readability and maintainability.

The built-in slice() function creates a slice object that can be used anywhere a slice operation is run.


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)

Operation results:


[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 of slice object s. You can get information about this object through the s.start, s.stop, and s.step attributes, respectively. Such as:


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)

Results:


[2, 5]
2
8
3

In addition, slices can be mapped to sequences of a specific size by using the indices(size) method. This returns one (start,stop,step) tuple, all of which are properly bounded (IndexError exceptions can be avoided when indexing), such as:


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

Results:


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


Related articles: