1

I have following code:

from re import match, compile

list1 = ['AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345']
list2 = ['AB12345', 'WLADEK', 'AB12345', 'AB12345', 'STEFAN', 'AB12345', 'AB12345', 'AB12345', 'ZENEK']
def iterChecker(list):
    regex = compile("([A-Z]{2})(\d+)")
    checker = []
    for l in list:
        if regex.match(l):
            checker.append(l)
            if len(checker) == len(list):
                print("Everything is ok")
        else:
            print("Elements that do not match: %s" % l)

iterChecker(list1)
print("###################")
iterChecker(list2)

The output:

Everything is ok
###################
Elements that do not match: WLADEK
Elements that do not match: STEFAN
Elements that do not match: ZENEK

My question is, how to check if all iterables match the condition. In this example, list elements should matches regex. I think, my solution for this problem is 'clumsy' and not 'elegant'. I was reading about all(), but have failed with inplementation.

Any suggestion to improve this code?

perissf
  • 15,979
  • 14
  • 80
  • 117
Fangir
  • 131
  • 6
  • 16

2 Answers2

1

To check that all iterables match, just have a flag that is assumes they do, but is false if any doesn't match. E.g (I havne't ran this code).

def iterChecker(list):
    regex = compile("([A-Z]{2})(\d+)")
    checker = []
    all_match = True
    for l in list:
        if regex.match(l):
            checker.append(l)
            if len(checker) == len(list):
                print("Everything is ok")
        else:
            all_match = False
            print("Elements that do not match: %s" % l)
    if all_match:
        print("All match")
Ali
  • 11
  • 1
0

Using the all statement:

from re import compile

list1 = ['AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345', 'AB12345']
list2 = ['AB12345', 'WLADEK', 'AB12345', 'AB12345', 'STEFAN', 'AB12345', 'AB12345', 'AB12345', 'ZENEK']

regex = compile("([A-Z]{2})(\d+)")

print all(regex.match(element) for element in list1)
print all(regex.match(element) for element in list2)
Elmex80s
  • 3,428
  • 1
  • 15
  • 23