I want to get a subarray in python 3. I have tried the following.
a = ['abcdefgh', 'abcdefgh' , 'abcdefgh']
print (a[0][3:6])
print (a[1][2:6])
print (a[0:2][3:6])
I get the first two results as expected. But I am not able to obtain the desired result for the 3rd print statement.
Output :
def
cdef
[]
Desired Output :
def
cdef
['def', 'def']
Can anyone tell me how to obtain it
To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.
slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.
Use Arrays. copyOfRange() method to get a subarray.
Given an array of numbers, return true if there is a subarray that sums up to a certain number n . A subarray is a contiguous subset of the array. For example the subarray of [1,2,3,4,5] is [1,2,3] or [3,4,5] or [2,3,4] etc. In the above examples, [2, 3] sum up to 5 so we return true .
Use list comprehension for this
print ([i[3:6] for i in a[0:2]])
This will work. It will iterate over elements at index 0 and 1 and will slice the array as expected.
[x[3:6] for x in a[0:2]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With