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.
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?
CodePudding user response:
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")
CodePudding user response:
You are changing is_in which affect outer loop (while) but not inner loop (for), add break
to also terminate inner loop that is
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
break
else:
print('No')
break
CodePudding user response:
run this code. note that there is no need to use while
in this code!
counter = 0
for item in mcr_coord_lst:
if pq_columns.match(item):
counter = 1
if counter >= 5:
break
if counter >=5:
print("YES")
else:
print("NO")