I have a structure with an x amount of lists in lists, and each list an x amount of tuples. I don't know beforehand how many nested lists there are, or how many tuples in each list.
I want to make dictionaries out of all the tuples and because I don't know the depth of the lists I want to use recursion. What I did was
def tupleToDict(listOfList, dictList):
itemDict = getItems(list) # a function that makes a dictionary out of all the tuples in list
dictList.append(itemDict)
for nestedList in listOfList:
getAllNestedItems(nestedList, dictList)
return dictList
this works, but I end up with a huge list at the end. I would rather return the itemDict at every round of recursion. However, I don't know how to (if it is possible) return a value without stopping the recursion.
You're looking for yield:
def tupleToDict(listOfList):
yield getItems(listofList)
for nestedList in listOfList:
for el in getAllNestedItems(nestedList):
yield el
In Python 3.3+, you can replace the last two lines with a yield from.
You may want to rewrite your function to be iterative:
def tupleToDict(listOfList):
q = [listOfList]
while q:
l = q.pop()
yield getItems(l)
for nestedList in listOfList:
q += getAllNestedItems(nestedList)
Who are you going to return it to? I mean if your thread is busy running the recursive algorithm, who gets the "interim results" to process?
Best bet is to tweak your algorithm to include some processing before it recurses again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With