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 check if enough specific elements are in a list?

I am trying to check if at least five items in my list have the following format: r"P\d+:Q\d+". So, these are accepted:

P14:Q52
P32:Q65
P1000:Q23423
:
:
etc.

I have a list of cell ranges like below:

mcr_coord_lst = [mcr.coord for mcr in worksheet.merged_cells.ranges]

mcr_coord_lst
['P58239:Q58239',
 'P58234:Q58234',
 'P58235:Q58235',
 'P58236:Q58236',
 'P58237:Q58237',
 'P58238:Q58238',
 'P58229:Q58229',
 'P58230:Q58230',
 'P58231:Q58231',
 'P58232:Q58232',
 'P58233:Q58233',
 'P58224:Q58224',
 'P58225:Q58225',
 'P58226:Q58226',
:
:
 'A123:Q324234',
:
:
]

I set up a counter and add to the counter if the item in my list matches pq_columns = re.compile(r"P\d+:Q\d+"). If the counter >= 5, then I break the loop and return 'Yes'. However, this result is returning 'Yes'for all of the items in my list and I am not sure what I am doing wrong.

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

counter = 0
is_in = False
while is_in == False:
    for item in mcr_coord_lst:
        if pq_columns.match(item):
            counter += 1
            if counter >= 5:
                print('Yes')
                is_in = True
        else:
            print('No')
            break

This code outputs:

Yes
Yes
...
Yes
Yes
Yes
:
:

Can you help me fix my code? Or do you recommend another way to do what I am trying to do?

>Solution :

Using a list comprehension we can try:

lst_filter = [x for x in mcr_coord_lst if re.search(r'^P\d+:Q\d+$', x)]
if len(lst_filter) >= 5:
    print("list is valid")
else:
    print("list is not valid")
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