Detailed Explanation of python Programming slice and indices Function Usage Examples

  • 2021-12-04 19:13:10
  • OfStack

1 In general, the built-in slice () function creates a slicing object that can be used wherever slicing is allowed.

The following is a brief introduction to slice:


# slice  Two usages 
class slice(stop)
class slice(start, stop[, step])

Returns a value representing the value of the range(start, stop, step) The slice object of the specified index set. Where the start and step parameters default to None . A slice object has a read-only data property that returns only the corresponding parameter value (or its default value) start , stop And step . They have no other explicit functions; However, they will be used by NumPy and other third-party extensions.

Slice objects are also generated when using extended index syntax. For example: a[start:stop:step] Or a[start:stop, i] .

See itertools. islice () for an alternative version of the return iterator.


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

If you have an instance of an slice object, s, you can get information about the object through the s. atart, s. stop, and s. step attributes, respectively. Example:


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

The following is the official explanation of indices:

slice. indices (self, length)

This method takes an integer parameter length and calculates how the information about the slice should be described when the slice object is applied to a sequence of entries of the specified length in length. Its return value is a tuple composed of 3 integers; These numbers are the start and stop index numbers and step step size values of the slices, respectively. If the index number is missing or out of bounds, it will be treated as a regular continuous slice.

All values have been properly restricted within the bounds (IndexError exceptions can be avoided when operating as indexes) example:


s = 'HelloWorld'
a.indices(len(s))
# (5, 10, 2)
for i in range (*a.indices(len(s))):
    print(s[i])
# w
# r
# d

The above is the detailed explanation of python programming slice and indices use example details, more about python programming slice and indices information please pay attention to other related articles on this site!


Related articles: