Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list out of a tuple of tuples

I have a tuple of tuples like this: t = ((4, 3), (2, 9), (7, 2), ...), where the first element in each nested tuple (i.e. t[i][0]) can range from 1 to 11 without repetition, but not necessarily every integer between 1 and 11 will be present.

I want to create a list (or tuple) r based on t, in the following way:

The resulting list r has a length of 11 exactly. For each index j in r, if j + 1 === t[i][0] for any i, then r[j] = t[i][1], otherwise r[j] = 0.

This can be done by initializing r to [0] * 11 first, and then loop through t to assign t[i][1] to r[t[i][0] - 1]:

t = ((4, 3), (2, 9), (7, 2), (10, 1))
r = [0] * 11
for item in t:
    r[item[0] - 1] = item[1]

r = [0, 9, 0, 3, 0, 0, 2, 0, 0, 1, 0]

But is there any more efficient way (a functional way, maybe)?

like image 661
skyork Avatar asked Oct 12 '25 01:10

skyork


2 Answers

How about:

>>> t
((4, 3), (2, 9), (7, 2), (10, 1))
>>> d = dict(t)
>>> [d.get(el, 0) for el in xrange(1, 12)]
[0, 9, 0, 3, 0, 0, 2, 0, 0, 1, 0]
like image 59
Jon Clements Avatar answered Oct 14 '25 15:10

Jon Clements


I would create a dictionary from t and populate r using lookups

t = ((4, 3), (2, 9), (7, 2))
d_t = dict(t)
r = [0]*11
r = [d_t[i+1] if i + 1 in d_t else r[i] for i, x in enumerate(r)]
print r
[0, 9, 0, 3, 0, 0, 2, 0, 0, 0, 0]
like image 45
iruvar Avatar answered Oct 14 '25 14:10

iruvar