Reputation: 9804
I am looking for a more pythonic way to loop though a list starting an an index then return the values contained in sub-lists eg:
values = [[1,2], [2], [1,3,4]]
n=1
for i, item in enumerate(values[n:]):
i += n
if i < len(values):
for sub_value in values[i]:
print("index: "+str(i)+ " list: "+str(item)+ " sub value: "+str(sub_value))
The code works as intended but is pretty ugly, any ideas to simplify it?
Upvotes: 2
Views: 4405
Reputation: 7049
I'm going to take a swing here and guess that you are trying to make a simple python function that loops through a list and prints out every element in the sublists. Here is the easiest way to do it:
def get_sublists(start=0):
values = [[1,2], [2], [1,3,4]]
index = start
item = 0
for value in values[index:]:
for sub_value in value:
print("Item: %s // Index: %s // List: %s // Sub Value: %s" % (item, index, values[index], sub_value))
item += 1
index += 1
get_sublists(1)
This will print out the following:
Item: 0 // Index: 1 // List: [2] // Sub Value: 2
Item: 1 // Index: 2 // List: [1, 3, 4] // Sub Value: 1
Item: 2 // Index: 2 // List: [1, 3, 4] // Sub Value: 3
Item: 3 // Index: 2 // List: [1, 3, 4] // Sub Value: 4
I am not 100% sure about the question because it is a bit ambigous, so let me know if you have any further modifications.
Upvotes: 0
Reputation: 393
I'm not sure I completely understand what you are trying to achieve.If you want to print a flat list of the items from index 1 you could do this:
[item for sublist in values[1:] for item in sublist]
which produces:
[2, 1, 3, 4]
Upvotes: 2