Saar Gamzo
Saar Gamzo

Reputation: 53

Python Comprehensions

I've got a list of tuples, each tuple looks like (i,x).

I need to return a new list (using a comprehension only) that each value will be in the "right" index. If index is missing, we'll put the value -1000 to fill the gap.

For example:

Input: [(4,9), (0,2), (1,4), (3,2)]
Output should be: [2, 4, -1000, 2, 9]

I was trying to use index function, I'm trying to get the index of the tuple (1,2), while I "know" only the first element, the second can be anything. I want to get the index of the tuple (1,2) by search (1,___), is that possible?

    return [sorted(L)[sorted(L).index((i,))][1] if i in [sorted(L)[j][0] for j in range(0,len(L))] else -1000 for i in range(sorted(L)[len(L)-1][0]+1)]

Thank you all for help!

Upvotes: 0

Views: 58

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27650

With the help of a dictionary that maps indices to values, so we can easily and efficiently get the value for an index:

[g(i, -1000) for g in [dict(L).get] for i in range(max(L)[0] + 1)]

Try it online!

Upvotes: 1

Related Questions