Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- a[start:end] # items start through end-1
- a[start:] # items start through the rest of the array
- a[:end] # items from the beginning through end-1
- a[:] # a copy of the whole array
- a[start:end:step] # start through not past end, by step
- a[-1] # last item in the array
- a[-2:] # last two items in the array
- a[:-2] # everything except the last two items
- +---+---+---+---+---+
- | H | e | l | p | A |
- +---+---+---+---+---+
- 0 1 2 3 4 5
- -5 -4 -3 -2 -1
- >>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
- >>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
- >>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
- >>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]]
- >>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ]
- >>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]
- >>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]]
- >>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
- >>> class slicee:
- ... def __getitem__(self, item):
- ... return `item`
- ...
- >>> slicee()[0, 1:2, ::5, ...]
- '(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'
- >>> r=[1,2,3,4]
- >>> r[1:1]
- []
- >>> r[1:1]=[9,8]
- >>> r
- [1, 9, 8, 2, 3, 4]
- >>> r[1:1]=['blah']
- >>> r
- [1, 'blah', 9, 8, 2, 3, 4]
- >>> x = [1,2,3,4,5,6]
- >>> x[::-1]
- [6,5,4,3,2,1]
- >>> x = [1,2,3,4,5,6]
- >>> x[::-2]
- [6,4,2]
- sliceable[start:stop:step]
- +---+---+---+---+---+---+
- | P | y | t | h | o | n |
- +---+---+---+---+---+---+
- 0 1 2 3 4 5
- -6 -5 -4 -3 -2 -1
- sequence[start:stop:step]
- my_list[-9:]
- my_list[-9:None:None]
- my_list[-9:len(my_list):1]
- list_copy = sequence[:]
- del my_list[:]
- last_nine_slice = slice(-9, None)
- >>> list(range(100))[last_nine_slice]
- [91, 92, 93, 94, 95, 96, 97, 98, 99]
- >>> length = 100
- >>> last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
- >>> list_last_nine = list(last_nine)
- >>> list_last_nine
- [91, 92, 93, 94, 95, 96, 97, 98, 99]
- Python indexes and slices for a six-element list.
- Indexes enumerate the elements, slices enumerate the spaces between the elements.
- Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
- Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
- +---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
- | a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
- +---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
- Slice from front: : 1 2 3 4 5 : a[-2]==4
- Slice from rear: : -5 -4 -3 -2 -1 :
- b=a[:]
- b==[0,1,2,3,4,5] (shallow copy of a)
- [a:b:c]
- len = length of string, tuple or list
- c -- default is +1. The sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward.
- a -- When c is positive or blank, default is 0. When c is negative, default is -1.
- b -- When c is positive or blank, default is len. When c is negative, default is -(len+1).
- In forward direction, starts at 0 and ends at len-1
- In backward direction, starts at -1 and ends at -len
- -len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1
- ...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , ....
- 0 1 2 3 4 5 6 7 8 9 10 11
- a s t r i n g
- -9 -8 -7 -6 -5 -4 -3 -2 -1
- >>> l1
- [2, 3, 4]
- >>> l1[:]
- [2, 3, 4]
- >>> l1[::-1] # a default is -1 , b default is -(len+1)
- [4, 3, 2]
- >>> l1[:-4:-1] # a default is -1
- [4, 3, 2]
- >>> l1[:-3:-1] # a default is -1
- [4, 3]
- >>> l1[::] # c default is +1, so a default is 0, b default is len
- [2, 3, 4]
- >>> l1[::-1] # c is -1 , so a default is -1 and b default is -(len+1)
- [4, 3, 2]
- >>> l1[-100:-200:-1] # Interesting
- []
- >>> l1[-1:-200:-1] # Interesting
- [4, 3, 2]
- >>> l1[-1:-1:1]
- []
- >>> l1[-1:5:1] # Interesting
- [4]
- >>> l1[1:-7:1]
- []
- >>> l1[1:-7:-1] # Interesting
- [3, 2]
- (from:to:step)
- (:to:step)
- (from::step)
- (from:to)
- def range(start=0, stop, step=1): # illegal syntax, but that's the effect
- i = start
- while (i < stop if step > 0 else i > stop):
- yield i
- i += step
- def this_is_how_slicing_works(seq, start=None, stop=None, step=1):
- if start is None:
- start = (0 if step > 0 else len(seq)-1)
- elif start < 0:
- start += len(seq)
- if not 0 <= start < len(seq): # clip if still outside bounds
- start = (0 if step > 0 else len(seq)-1)
- if stop is None:
- stop = (len(seq) if step > 0 else -1) # really -1, not last element
- elif stop < 0:
- stop += len(seq)
- for i in range(start, stop, step):
- if 0 <= i < len(seq):
- yield seq[i]
- mylist[X:Y]
- a[start:end:step]
- m[::,0:2:] ## slice the first two columns
- >>> l=[12,23,345,456,67,7,945,467]
- >>> l[len(l):-len(l)-1:-1]
- [467, 945, 7, 67, 456, 345, 23, 12]
- >>> l[:-len(l)-1:-1]
- [467, 945, 7, 67, 456, 345, 23, 12]
- >>> l[len(l)::-1]
- [467, 945, 7, 67, 456, 345, 23, 12]
- >>> l[::-1]
- [467, 945, 7, 67, 456, 345, 23, 12]
- >>> l[-1:-len(l)-1:-1]
- [467, 945, 7, 67, 456, 345, 23, 12]
- r = [1, 'blah', 9, 8, 2, 3, 4]
- >>> r[1:4] = []
- >>> r
- [1, 2, 3, 4]
- >>> 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]
- >>> a = slice(10, 50, 2)
- >>> a.start
- 10
- >>> a.stop
- 50
- >>> a.step
- 2
- >>>
- Index:
- ------------>
- 0 1 2 3 4
- +---+---+---+---+---+
- | a | b | c | d | e |
- +---+---+---+---+---+
- 0 -4 -3 -2 -1
- <------------
- Slice:
- <---------------|
- |--------------->
- : 1 2 3 4 :
- +---+---+---+---+---+
- | a | b | c | d | e |
- +---+---+---+---+---+
- : -4 -3 -2 -1 :
- |--------------->
- <---------------|
- In [122]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
- In [123]: alpha
- Out[123]: ['a', 'b', 'c', 'd', 'e', 'f']
- In [124]: alpha[0]
- Out[124]: 'a'
- In [127]: alpha[0] = 'A'
- In [128]: alpha
- Out[128]: ['A', 'b', 'c', 'd', 'e', 'f']
- In [129]: alpha[0,1]
- ---------------------------------------------------------------------------
- TypeError Traceback (most recent call last)
- <ipython-input-129-c7eb16585371> in <module>()
- ----> 1 alpha[0,1]
- TypeError: list indices must be integers, not tuple
- In [130]: alpha[0:1]
- Out[130]: ['A']
- In [131]: alpha[0:1] = 'a'
- In [132]: alpha
- Out[132]: ['a', 'b', 'c', 'd', 'e', 'f']
- In [133]: alpha[0:2] = ['A', 'B']
- In [134]: alpha
- Out[134]: ['A', 'B', 'c', 'd', 'e', 'f']
- In [135]: alpha[2:2] = ['x', 'xx']
- In [136]: alpha
- Out[136]: ['A', 'B', 'x', 'xx', 'c', 'd', 'e', 'f']
- In [137]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
- In [142]: alpha[1:5:2]
- Out[142]: ['b', 'd']
- In [143]: alpha[-1:-5:-2]
- Out[143]: ['f', 'd']
- In [144]: alpha[1:5:-2]
- Out[144]: []
- In [145]: alpha[-1:-5:2]
- Out[145]: []
- def py_slice_get_indices_ex(obj, start=None, stop=None, step=None):
- length = len(obj)
- if step is None:
- step = 1
- if step == 0:
- raise Exception("Step cannot be zero.")
- if start is None:
- start = 0 if step > 0 else length - 1
- else:
- if start < 0:
- start += length
- if start < 0:
- start = 0 if step > 0 else -1
- if start >= length:
- start = length if step > 0 else length - 1
- if stop is None:
- stop = length if step > 0 else -1
- else:
- if stop < 0:
- stop += length
- if stop < 0:
- stop = 0 if step > 0 else -1
- if stop >= length:
- stop = length if step > 0 else length - 1
- if (step < 0 and stop >= start) or (step > 0 and start >= stop):
- slice_length = 0
- elif step < 0:
- slice_length = (stop - start + 1)/(step) + 1
- else:
- slice_length = (stop - start - 1)/(step) + 1
- return (start, stop, step, slice_length)
- In [21]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
- In [22]: s = slice(None, None, None)
- In [23]: s
- Out[23]: slice(None, None, None)
- In [24]: s.indices(len(alpha))
- Out[24]: (0, 6, 1)
- In [25]: range(*s.indices(len(alpha)))
- Out[25]: [0, 1, 2, 3, 4, 5]
- In [26]: s = slice(None, None, -1)
- In [27]: range(*s.indices(len(alpha)))
- Out[27]: [5, 4, 3, 2, 1, 0]
- In [28]: s = slice(None, 3, -1)
- In [29]: range(*s.indices(len(alpha)))
- Out[29]: [5, 4]
- variable[number1:number2]
- for any n, lst = lst[:n] + lst[n:]
- lst = range(10)
- lst[:-42] + lst[-42:] == lst
- s[start:end:step]
- # mostly used variations
- s[start:end]
- s[start:]
- s[:end]
- # step related variations
- s[:end:step]
- s[start::step]
- s[::step]
- # make a copy
- s[:]
- s[-5:] # start at the 5th index from the end of array,
- # thus returns the last 5 elements
- s[:-5] # start at index 0, end until the 5th index from end of array,
- # thus returns s[0:len(s)-5]
- s[::-1] # reversed slice
- s[len(s)::-1] # same as above, reversed slice
- s[0:len(s):-1] # empty list
- s[:len(s)+5] # same as s[:len(s)]
- s[-len(s)-5::] # same as s[0:]
- s[len(s)+5::-1] # same as s[len(s)::-1], same as s[::-1]
- # create our array for demonstration
- In [1]: s = [i for i in range(10)]
- In [2]: s
- Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- In [3]: s[2:] # from index 2 to last index
- Out[3]: [2, 3, 4, 5, 6, 7, 8, 9]
- In [4]: s[:8] # from index 0 up to index 8
- Out[4]: [0, 1, 2, 3, 4, 5, 6, 7]
- In [5]: s[4:7] # from index 4(included) up to index 7(excluded)
- Out[5]: [4, 5, 6]
- In [6]: s[:-2] # up to second last index(negative index)
- Out[6]: [0, 1, 2, 3, 4, 5, 6, 7]
- In [7]: s[-2:] # from second last index(negative index)
- Out[7]: [8, 9]
- In [8]: s[::-1] # from last to first in reverse order(negative step)
- Out[8]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
- In [9]: s[::-2] # all odd numbers in reversed order
- Out[9]: [9, 7, 5, 3, 1]
- In [11]: s[-2::-2] # all even numbers in reversed order
- Out[11]: [8, 6, 4, 2, 0]
- In [12]: s[3:15] # end is out of range, python will set it to len(s)
- Out[12]: [3, 4, 5, 6, 7, 8, 9]
- In [14]: s[5:1] # start > end, return empty list
- Out[14]: []
- In [15]: s[11] # access index 11(greater than len(s)) will raise IndexError
- ---------------------------------------------------------------------------
- IndexError Traceback (most recent call last)
- <ipython-input-15-79ffc22473a3> in <module>()
- ----> 1 s[11]
- IndexError: list index out of range
- #!/usr/bin/env python
- def slicegraphical(s, lista):
- if len(s) > 9:
- print """Enter a string of maximum 9 characters,
- so the printig would looki nice"""
- return 0;
- # print " ",
- print ' '+'+---' * len(s) +'+'
- print ' ',
- for letter in s:
- print '| {}'.format(letter),
- print '|'
- print " ",; print '+---' * len(s) +'+'
- print " ",
- for letter in range(len(s) +1):
- print '{} '.format(letter),
- print ""
- for letter in range(-1*(len(s)), 0):
- print ' {}'.format(letter),
- print ''
- print ''
- for triada in lista:
- if len(triada) == 3:
- if triada[0]==None and triada[1] == None and triada[2] == None:
- # 000
- print s+'[ : : ]' +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] == None and triada[1] == None and triada[2] != None:
- # 001
- print s+'[ : :{0:2d} ]'.format(triada[2], '','') +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] == None and triada[1] != None and triada[2] == None:
- # 010
- print s+'[ :{0:2d} : ]'.format(triada[1]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] == None and triada[1] != None and triada[2] != None:
- # 011
- print s+'[ :{0:2d} :{1:2d} ]'.format(triada[1], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] != None and triada[1] == None and triada[2] == None:
- # 100
- print s+'[{0:2d} : : ]'.format(triada[0]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] != None and triada[1] == None and triada[2] != None:
- # 101
- print s+'[{0:2d} : :{1:2d} ]'.format(triada[0], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] != None and triada[1] != None and triada[2] == None:
- # 110
- print s+'[{0:2d} :{1:2d} : ]'.format(triada[0], triada[1]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif triada[0] != None and triada[1] != None and triada[2] != None:
- # 111
- print s+'[{0:2d} :{1:2d} :{2:2d} ]'.format(triada[0], triada[1], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
- elif len(triada) == 2:
- if triada[0] == None and triada[1] == None:
- # 00
- print s+'[ : ] ' + ' = ', s[triada[0]:triada[1]]
- elif triada[0] == None and triada[1] != None:
- # 01
- print s+'[ :{0:2d} ] '.format(triada[1]) + ' = ', s[triada[0]:triada[1]]
- elif triada[0] != None and triada[1] == None:
- # 10
- print s+'[{0:2d} : ] '.format(triada[0]) + ' = ', s[triada[0]:triada[1]]
- elif triada[0] != None and triada[1] != None:
- # 11
- print s+'[{0:2d} :{1:2d} ] '.format(triada[0],triada[1]) + ' = ', s[triada[0]:triada[1]]
- elif len(triada) == 1:
- print s+'[{0:2d} ] '.format(triada[0]) + ' = ', s[triada[0]]
- if __name__ == '__main__':
- # Change "s" to what ever string you like, make it 9 characters for
- # better representation.
- s = 'COMPUTERS'
- # add to this list different lists to experement with indexes
- # to represent ex. s[::], use s[None, None,None], otherwise you get an error
- # for s[2:] use s[2:None]
- lista = [[4,7],[2,5,2],[-5,1,-1],[4],[-4,-6,-1], [2,-3,1],[2,-3,-1], [None,None,-1],[-5,None],[-5,0,-1],[-5,None,-1],[-1,1,-2]]
- slicegraphical(s, lista)
- +---+---+---+---+---+---+---+---+---+
- | C | O | M | P | U | T | E | R | S |
- +---+---+---+---+---+---+---+---+---+
- 0 1 2 3 4 5 6 7 8 9
- -9 -8 -7 -6 -5 -4 -3 -2 -1
- COMPUTERS[ 4 : 7 ] = UTE
- COMPUTERS[ 2 : 5 : 2 ] = MU
- COMPUTERS[-5 : 1 :-1 ] = UPM
- COMPUTERS[ 4 ] = U
- COMPUTERS[-4 :-6 :-1 ] = TU
- COMPUTERS[ 2 :-3 : 1 ] = MPUT
- COMPUTERS[ 2 :-3 :-1 ] =
- COMPUTERS[ : :-1 ] = SRETUPMOC
- COMPUTERS[-5 : ] = UTERS
- COMPUTERS[-5 : 0 :-1 ] = UPMO
- COMPUTERS[-5 : :-1 ] = UPMOC
- COMPUTERS[-1 : 1 :-2 ] = SEUM
- [Finished in 0.9s]
- >>> a
- array([[ 1, 2, 3, 4],
- [ 5, 6, 7, 8],
- [ 9, 10, 11, 12]])
- >>> a[:2,0:3:2]
- array([[1, 3],
- [5, 7]])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement