1/12/2018

python list, numpy slicing

Oh.. I seem to be old.. I need a memo everything..
This is memo for me about list slicing.

nums = list(range(5))
print(nums)      #[0, 1, 2, 3, 4]
print(nums[2:4]) #[2, 3]
print(nums[2:])  #[2, 3, 4] 
print(nums[:2])  #[0, 1]
print(nums[:])   #[0, 1, 2, 3, 4]
print(nums[:-1]) #[0, 1, 2, 3]
nums[2:4] = [8,9]
print(nums)      #[0, 1, 8, 9, 4]

result
[0, 1, 2, 3, 4]
[2, 3]
[2, 3, 4]
[0, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3]
[0, 1, 8, 9, 4]


numpy slicing
import numpy as np

a = np.array([1, 2, 3, 4, 5])
print(a[1:3]) #array [2 3]
print(a[-1]) #5
a[0:2] = 9
print(a) #array [9 9 3 4 5]
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(b)
#array
#[[ 1  2  3  4]
# [ 5  6  7  8]
# [ 9 10 11 12]]

print(b[:,1]) #array [2 6 10]
print(b[-1])      #array [9 10 11 12]
print(b[-1,:])    #array [9 10 11 12]
print(b[-1, ...]) #array [9 10 11 12]

print(b[0:2, :])
#array#[[1 2 3 4]# [5 6 7 8]]
๐Ÿ˜€

No comments:

Post a Comment