1.11 命名切片

你的程序有很多硬编码的片段下标,你不能直接看到,然后你想要清理代码。

[En]

Your program has a lot of hard-coded slice subscript that you can’t see directly, and then you want to clean up the code.

假设您有一段从记录字符串的固定位置提取特定数据字段的代码:

[En]

Suppose you have a piece of code to extract a specific data field from a fixed position in a record string:

record = '....................100 .......513.25 ..........'
cost = int(record[20:23]) * float(record[31:37])

事实上,命名切片可用于避免大量难以理解的硬编码下标,并使代码更具可读性。

[En]

In fact, named slices can be used to avoid a large number of hard-coded subscripts that are incomprehensible and make the code more readable.

SHARES = slice(20, 23)
PRICE = slice(31, 37)
cost = int(record[SHARES]) * float(record[PRICE])

一般来说,如果代码中有大量的硬编码下标,代码的可读性和可维护性会大大降低。命名切片是更清楚地表达代码想要做什么的好方法。

[En]

Generally speaking, if there are a large number of hard-coded subscripts in the code, the readability and maintainability of the code will be greatly reduced. Naming slices is a good way to express what your code wants to do more clearly.

内置的函数 slice()函数创建了一个切片对象,可以被使用在任何切片允许使用的地方。比如:

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

items[a] = [10, 11]  # items = [0, 1, 10, 11, 4, 5, 6]

del items[a]  # item = [0, 1, 4, 5, 6]

如果你有一个切片对象 a,你可以分别调用它的 a.starta.stopa.step属性来获取更多的信息。比如:

a = slice(5, 50, 2)
a.start  # 5
a.stop  # 50
a.step  # 2

另外,你还能通过调用切片的 indices(size)方法将它映射到一个确定大小的序列上,这个方法返回一个三元组(start, stop, step),所有值都会被合适的缩小以满足边界限制,从而避免出现 IndexError异常。比如:

s = 'HelloWorld'
a = slice(5, 10, 2)
d = a.indices(len(s))
"""
d = (5, 10, 2)
"""

for i in range(*d):
    print(s[i])
"""输出结果
W
r
d
"""

Original: https://www.cnblogs.com/L999C/p/15731595.html
Author: Abu11
Title: 1.11 命名切片

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/510424/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球