In Python, is there any counter
available during the list comprehension as it would be in case of a for
loop?
It would be more clear why I need a counter, with this example:
I wish to achieve the following:
Initial List: ['p', 'q', 'r', 's']
Desired List: [(1, 'P'), (2, 'Q'), (3, 'R'), (4, 'S')]
In the desired list, first element of every tuple are ordinal numbers. If it were just flat list, I could have used zip
to achieve this. But however, the list I am dealing with is nested, three level deep (think of hierarchical data), and it is generated through list comprehension.
So, I was wondering is there any way to introduce those ordinal numbers during list comprehension. If not, what would be the best possible solution.
P.S. : Here the lower case letters are converted to uppercase, but that is not a part of problem, think of it as just a data conversion.
Code:
allObj = Category.objects.all()
tree =[(_, l1.name, [(__, l2.name, [(___, l3.name) for l3 in allObj if l3.parentid == l2.categoryid]) for l2 in allObj if l2.parentid == l1.categoryid]) for l1 in allObj if l1.parentid == None]
allObj
contains data from table category, which in turn contains hierarchical data represented in the form of Adjacency List.
I have put _
where I need ordinal numbers to be. Notice that the list is nested, so there will be a separate counter at each level represented by 1, 2 & 3 _
s.