Python Cookbook 笔记一

2018-04-26  本文已影响0人  AIfred

前言

书来源

切片器slice

切片器是解决硬编码的一个好方法
硬编码(Hard coding)

Hard coding (also hard-coding or hardcoding) is the software development practice of embedding an input or configuration data directly into the source code of a program or other executable object, or fixed formatting of the data, instead of obtaining that data from external sources or generating data or formatting in the program itself with the given input.

>>> 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]
>>> items
[0, 1, 4, 5, 6]

indices的使用

indices是slice类实例的一个方法,这个方法很好地解决了IndexError异常的问题
indices解释,来自官方帮助文档

indices(...) method of builtins.slice instance
S.indices(len) -> (start, stop, stride)

Assuming a sequence of length len, calculate the start and stop
indices, and the stride length of the extended slice described by
S. Out of bounds indices are clipped in a manner consistent with the
handling of normal slices.

上一篇 下一篇

猜你喜欢

热点阅读