Home > OS >  Python Comprehensions
Python Comprehensions

Time:04-09

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

  • i = index

  • x = value

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?

  • ___ is a positive integer
    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)]
  • I can use list/dict/set comprehension, single line.

Thank you all for help!

CodePudding user response:

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!

  • Related