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

How to combine like elements in list?

I’m trying to reorganize my list according to its peers.

I have this list:

['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_CURITIBA_A807_M-PRESS_HPA']

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

and i want to do something like this:

['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']

the element ‘datetime’ must be the first element in list, but i think i can do this after reordered list

>Solution :

Full Code

data = ['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM',
        'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']
data.remove("datetime") # removing datetime as it is the odd one in the list
data = sorted(data, key=lambda x: x.split("-")[-1])# sorting based on the last element ie. element after '-'
data.insert(0, "datetime") # Inserting the odd element 'datetime' back
print(data)

Output

['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']

Hope this helps. happy Coding 🙂

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