I have a nested list (list of lists) where each sublist might contain one or more elements (integers) but some are even empty:
mynestedlist = [[], [], [], [4,10], [4], [10]]
In addition I have another list of the same length (all integers):
otherlist = [2,4,14,32,21,12]
Now I'd like to get a combined list of tuples for elements where my nested list element is not empty. Actually each tuple should contain elements from both lists.
For example the first non-empty list in mynestedlist is the 4th which is [4,10]. The corresponding element from otherlist is 32. This information should be coerced to two tuples (32,4) and (32,10). So if there are more than one entry in the sublist of mynestedlist than multiple tuples should be created.
Finally the output should be [(32,4),(32,10),(21,4),(12,10)]. How can this be done in an efficient way?
So what I tried so far is
*) to check if a sublist is empty using the sum of the sublist
[sum(x)>0 for x in mynestedlist]
*) to combine both lists into a dictionary
combined_list = dict(zip(otherlist,mynestedlist))
I am not sure at all if this is the way to go?
This is actually pretty straightforward with a list comprehension,
>>> [(b, e) for a, b in zip(mynestedlist, otherlist) for e in a]
[(32, 4), (32, 10), (21, 4), (12, 10)]
You can use itertools.izip if on Python 2.x and have long lists.
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