1

How to make function that can execute list comprehension(zip?) The sublists should have different lengths which are given.

Example:

myList = [1,2,3,4,5,6,7,8,9]
   
myNum = (2,4,3)

Desired outcome:

newList = ['(1,2)', '(3,4,5,6)', '(7,8,9)']
buddemat
  • 4,552
  • 14
  • 29
  • 49
태주강
  • 23
  • 4
  • Watch out. `myList` is a list, but `myNum` is a tuple. A quick search brings an answer to your question; https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks. – Enis Arik Nov 17 '20 at 17:17

2 Answers2

1

If it does not have to be a List comprehension, you can solve it like this:

myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3)
prev = 0
newList = []
for i in myNum:
    newList.append(tuple(myList[prev:prev+i]))
    prev = prev+i 
Julio Reckin
  • 146
  • 1
  • 10
0

try this one:

myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3) 
newList = [] 

for i in myNum:
   newList.append(tuple(myList[:i]))
   [ myList.pop(myList.index(x)) for x in myList[:i] ]
print(newList)

OR

myList = [1,2,3,4,5,6,7,8,9]
myNum = (2,4,3) 
newList = [] 
x = 0
for i in myNum:
   if x == 0:
       newList.append(tuple(myList[:i]))
       x = myList[:i][-1] 
   else:
       end_index = myList[myList.index(x)+1 : myList.index(x)+1+i]
       newList.append(tuple(end_index))
       x = end_index[-1]
print(newList)
zankoAN
  • 327
  • 2
  • 6