Python implements the method of naming slices

不言
Release: 2018-10-15 14:17:53
forward
2138 people have browsed it

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)
Copy after login

Running result:

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

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)
Copy after login

Result:

[2, 5]
2
8
3
Copy after login

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])
Copy after login

Result:

(2, 5, 1)
2:l
3:l
4:o
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template