I am having to deal with either lists or lists of lists. I find that my current method is not very efficient as I have to define two separate methods for doing things and effectively write them out twice. Is there a more efficient way to check if incoming data is a list or list of lists and then proceed accordingly (I usually want to act on each item of incoming data and output a list or list of lists that matches structure of the incoming data). Here's an example of me dealing with it:
if not any(isinstance(item, list) for item in keys):
userStrings = []
for key in keys[index]:
userStrings[index].extend(item.GetUserStrings().GetValues(key))
else:
userStrings = [[] for i in range(len(rhObjects))]
for index, item in enumerate(rhObjects):
for key in keys[index]:
userStrings[index].extend(item.GetUserStrings().GetValues(key))
What if i encounter something even more complex where its a list of lists of lists etc. This method will not work...ideas?
Thanks!
This doesn't seem to be clear enough. Let's start over. Imagine that I have a list of lists, a list, or even a list of lists of lists of objects:
_list = [["X","Y","Z"],["X","Y","Z",["X","Y","Z"]],["X","Y","Z"]]
_list2 = ["X","Y","Z"]
_list3 = [["X","Y","Z"],["X","Y","Z"]]
All I want to do is perform a simple function on each object from these lists (append "A" to each object) or create a whole new object but in a fashion that matches structure of the original input list. Example functions:
def my_function(obj):
return obj + "A"
def my_function2(obj):
return newObj
DESIRED OUTPUT:
_newList = [["XA","YA","ZA"],["XA","YA","ZA",["XA","YA","ZA"]],["XA","YA","ZA"]]
_newList2 = ["XA","YA","ZA"]
_newList3 = [["XA","YA","ZA"],["XA","YA","ZA"]]
or if used my_function2:
_newList = [["newObj","newObj","newObj"],["newObj","newObj","newObj",["newObj","newObj","newObj"]],["newObj","newObj","newObj"]]
Is there a way to make this like the user below suggested with two functions? One recursive? I am a total noob to recursion and the first approach that you saw on top was my way of checking for lists within the list, but its really not flexible. All/any help is appreciated!