How to split an array from an other array with the numbers of element to split in python
Hi,
I have 2 arrays like this :
names = ['georges','albert','kate','bradley','elizabeth','william','louis','charles']
iters = [2,2,4]
And browsing my array 'iters', I want to have 3 arrays like this :
arr1 = ['georges','albert']
arr2 = ['kate','bradley']
arr3 = ['elizabeth','william','louis','charles']
The first array has 2 elements because my first element in my array 'iters' is 2. The second array has 2 elements because my second element in my array 'iters' is 2. And finally my last array has 4 elements because my last element in my array 'iters' is 4.
Thanks in advance
CodePudding user response:
here is one way :
splited = []
prev = 0
for i in iters:
splited.append(names[prev:i prev])
prev = i
print(splited)
output:
>> [['georges', 'albert'], ['kate', 'bradley'], ['elizabeth', 'william', 'louis', 'charles']]
CodePudding user response:
If you do:
arrs = [names[sum(iters[:i]):sum(iters[:i 1])] for i in range(len(iters))]
then you will have:
print(arrs)
[['georges', 'albert'], ['kate', 'bradley'], ['elizabeth', 'william', 'louis', 'charles']]