Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Comprehensions

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

  • i = index

  • x = value

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

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!

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading