Given a list of lists where the number of lists, and the number of elements within is variable. For example:
import random import string bar = lambda: [random.choice(string.ascii_letters) for _ in range(random.randint(1,5))] branches = [bar() for _ in range(4)] >>> branches [['t'], ['S', 't'], ['Q'], ['M', 'a', 'J', 'x', 'Y']] I'm wondering if there is a more succinct way to create a list of tuples which index the list. Something more concise than this:
nodes = [] for branch in range(len(branches)): for node in range(len(branches[branch])): nodes.append((branch, node)) >>> nodes [(0, 0), (1, 0), (1, 1), (2, 0), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4)] Couldn't this be done with a list comprehension? I'm just having some trouble nailing it and am confident there's a brainiac out there with a big hammer.
The ultimate goal is to randomly visit each node once, and only once, and during the visit, to know exactly where the current node lies in the grand scheme of things. So I shuffle the result random.shuffle(nodes) and loop over it—using the tuple to access the original list via branches[node[0]][node[1]]. Better ideas are welcome.
[(branch, node) for branch in range(len(branches)) for node in range(len(branches[branch]))].