Reputation: 7381
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)?
Upvotes: 4
Views: 201
Reputation: 11002
Just use a mapping (by dictionary)
d = { v[0]:v[1] for i,v in enumerate(t) }
result = [ d[j+1] if j+1 in d else 0 for j in t ]
Upvotes: 1
Reputation: 250881
You can use dict
and a list comprehension with conditional expression:
>>> dic = dict(t)
>>> [dic[i] if i in dic else 0 for i in range(1, 12)]
[0, 9, 0, 3, 0, 0, 2, 0, 0, 1, 0]
Upvotes: 1
Reputation: 142106
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]
Upvotes: 6
Reputation: 23374
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]
Upvotes: 1