0

I would like to use 3 lists as arguments of a function. Maybe my entire logic is wrong on this, but what I'm trying to do is use two lists to create the iterators to parse the third list. The order is important, so the first element of the first and second list would give the first and last index etc.

My code gives only the first sublist, when of course I would like to have all of them.

A=[1, 3, 4, 6]
B=[3, 8, 5, 8]
C=['A', 'B','C', 'D', 'E', 'A', 'B', 'A', 'D']

def newlists(entirelist, initiating, terminating):
    for initindex in initiating:
        for termindex in terminating:

        parsed_list = entirelist[initindex:termindex]

        return parsed_list



all_sublists = newlists(C, A, B)

I need the following output or something similar to obtain the sublists:

all_sublists = [['B','C'],['D','E', 'A', 'B', 'A'],['E'],['B','A']]
1
  • I think you will first need to define parsed_list = [] at the beginning of your function and then, instead of parsed_list = entirelist[initindex:termindex] use this parsed_list.append(entirelist[initindex:termindex]) Commented Nov 1, 2018 at 9:23

2 Answers 2

1

You can use comprehension to get what you want:

A=[1, 3, 4, 6]
B=[3, 8, 5, 8]
C=['A', 'B','C', 'D', 'E', 'A', 'B', 'A', 'D']

def newlists(entirelist, initiating, terminating):
    return [entirelist[i:j] for i, j in zip(initiating, terminating)]

print(newlists(C, A, B))
#[['B', 'C'], ['D', 'E', 'A', 'B', 'A'], ['E'], ['B', 'A']]
Sign up to request clarification or add additional context in comments.

Comments

0

A solution without list comprehension and fancy zip function:

def newlists(entirelist, initiating, terminating):
    return map(lambda i, j: entirelist[i:j], initiating, terminating)

print(list(newlists(C,A,B)))
# => [['B', 'C'], ['D', 'E', 'A', 'B', 'A'], ['E'], ['B', 'A']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.