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

Get a element from list, from pair of 3

Hello I have a list in which elemnets are in pair of 3 list given below,

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']

in above list elements are coming in pair of 3 i.e. (”, ”, ‘5000’) one pair, (”, ‘2’, ”) second pair, (‘mm-dd-yy’, ”, ”) third pair and so on.

now i want to check ever 3 pairs in list and get the element which is not blank.

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

(”, ”, ‘5000’) gives ‘5000’

(”, ‘2’, ”) gives ‘2’

(‘mm-dd-yy’, ”, ”) gives ‘mm-dd-yy’

and if all three are blank it should return blank i.e.

(”, ”, ”) gives ” like last 2 pair in list

so from the above list my output should be:

required_list = ['5000','2','1000','mm-dd-yy','15','dd/mm/yy','3','200','2','mm-dd-yy','','']

>Solution :

as it is fixed you have to create 3 pairs each time you can do with for loop by specifying step in range(start,end,step)

labels = ['', '', '5000','', '2', '','', '', '1000','mm-dd-yy', '', '','', '', '15','dd/mm/yy', '', '', '', '3', '','', '', '200','', '2', '','mm-dd-yy', '', '','', '', '','', '', '']
res1=[]
for i in range(0,len(labels),3):
    res1.append(labels[i]+labels[i+1]+labels[i+2])
print(res1)

#List Comprehension
res2=[labels[i]+labels[i+1]+labels[i+2] for i in range(0,len(labels),3)]

print(res2)

Output:

['5000', '2', '1000', 'mm-dd-yy', '15', 'dd/mm/yy', '3', '200', '2', 'mm-dd-yy', '', '']
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