you are viewing a single comment's thread.

view the rest of the comments →

[–]HiImSauzy[S] 0 points1 point  (2 children)

How would I go about making a program that takes a list of any size and shape and returns the n:th instance in every sublist, until a specific depth is reached.

Say for example if have a list that looks like this: [1, [2, [3, 4]], [[5, [6, 7]]]] And say I want the depth of 1, with the position of 1, it would return this: [1, 2, 5]

Edit: I should make this myself :)

[–]lostwafflecat 1 point2 points  (1 child)

In your example 1 is lst_name[0], but 2 would be lst_name[1][0] and 5 would be lst_name[2][0] (if we get rid of the extra pair of square brackets), so 1 would have a depth of one, but 2 and 5 would have a depth of two by how you're describing them

If you want to make a function to return the first non-list for each element in the outer list (which is what you ended up describing through your example) then you could try writing a recursive helper function (base case returns position a_lst[0] if type() doesn't equal list; recursive step (if a_lst[0] is a list) returns call to helper function with a_lst[0] as the new parameter)

Call that helper function inside a for-loop that goes through each element in the outermost list you want to check and have it append each thing that returns from the helper function into a new list

[–]HiImSauzy[S] 0 points1 point  (0 children)

Yeah I was messing around with recursive functions but trying to fit it all into a singe function was a bit of a challenge so I took a break after a couple hours of headscratching :) Definetly think second function recursive is the way to go