Problem: How to clean up a hard-coded tile index everywhere
Solution: Name The Slice
Suppose some code is used to extract specific data from a fixed position in a string, such as from a flat file or a similar format: A flat file flat files is a record file that contains no relative relational structure:
# ###### #0123456789012345678901234567890123456789012345678901234567890123456789record=' .................... 100.......513.25...'cost =int (record[20:23]) *float (record[30:36])
Instead of doing this, you should name the slices: the code becomes much clearer by avoiding the use of many arcane hard-coded indexes.
# Name the slice Price=slice (30,36) # name the slice cost =int (Record[shares]) *float (Record[price])
In general, the built-in slice () function creates a slice object that can be used wherever a slice is allowed.
>>> items=[0,1,2,3,4,5,6]>>> a=slice (2,4)>>> Aslice (2, 4 , None)>>> items[a][2, 3]>>> items[2:4[2, 3]>> > items[a]=[77,88]>>>1, 4, 5, 6]del Items[a] >>>1, 4, 5, 6]
If you have an instance of slice object s, you can get information about the object by S.start, S.stop, and S.step properties, respectively.
>>> items=[0,1,2,3,4,5,6]>>> a=slice (2,4)>>> Aslice (2, 4 , None)>>> a.start2>>> a.stop4>>> a.step>>> b= Slice (1,5,2)>>> bslice (1, 5, 2)>>> b.start1>>> b.stop5>>> b.step
In addition, you can map slices to a sequence of a specific size by using the indices (size) method. This returns a (start,stop,step) tuple in which all values have been properly restricted within the bounds (as an index operation to avoid indexerror exceptions)
>>> items=[0,1,2,3,4,5,6]>>> A=slice (2,4)>>>Aslice (2, 4, None)>>>A.start2>>>A.stop4>>>A.step>>> B=slice (1,5,2)>>>Bslice (1, 5, 2)>>>B.start1>>>B.stop5>>>B.step2>>> s='HelloWorld'>>>A.indices (Len (s)) (2, 4, 1)>>>B.indices (Len (s)) (1, 5, 2)>>>items[a][2, 3]>>>items[b][1, 3]>>> forIinchRange (*A.indices (Len (s))):Print(S[i]) ll>>> forIinchRange (*B.indices (Len (s))):Print(S[i]) El>>> C=slice (0,8,2)
>>> C
Slice (0, 8, 2)
>>> for I in range (*c.indices (len (s))):
Print (S[i])
H
L
O
O
>>>
"Python Cookbook" "Data Structure and algorithm" 11. Name the Slice