I have a big list that its elements are also lists, and their elements also lists.
for example:
GrandFather= [Father1, Father2, Father3]
Father1= [Child1, Child2, Child3]
Father2= [Child4, Child5, Child6]
Father3= [Child7, Child8, Child9]
Child1 =[7,1]
Child2 =[6,2]
Child3 =[5,3]
Child4 =[4,4]
Child5 =[3,5]
Child6 =[2,6]
Child7 =[0,7]
Child8 =[1,8]
Child9 =[0,9]
So, if I have only the GrandFather List, and I want to access the leaves elements which are the elements inside each Child, I will have to write:
for father_index in GrandFather:
for child_index in GrandFather[father_index]:
for leaf_index in GrandFather[father_index][child_index]:
print( GrandFather[father_index][child_index][leaf_index ])
You can notice the complexity of accessing the leaves elements, actually the real list I have is much deeper than that. So, my question here is Is there a simpler way to access the leaves directly?
CodePudding user response:
There is no algorithm in the default Python libraries you can use itertools.chain.from_iterable
comes close, but does not yield the individual values in the children.
Luckily the algorithm is easy to write:
def flatten(l):
for value in l:
if isinstance(value, list):
yield from flatten(value)
else:
yield value
You can now iterate over each element with
for a in flatten(GrandFather):
print(a)
CodePudding user response:
Python for
loops iterate over elements, not indices. The actual loop would look like this:
for father in grandfather:
for child in father:
for leaf in child:
print(leaf)
As you can see, the nested loops are a bit annoying, but the complicated indexing is a figment of your imagination.