2017-02-15 97 views
1

我有以下代碼:Python中的所有iterables符合條件

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) 

輸出:

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

我的問題是,如何檢查是否所有iterables符合條件。在這個例子中,列表元素應該匹配regex。我認爲,我對這個問題的解決方案是「笨拙」,而不是「優雅」。我正在閱讀all(),但因實施失敗。

任何建議,以改善此代碼?

回答

1

要檢查所有迭代匹配,只需要一個標誌,假設它們是這樣做的,但如果有任何不匹配,則爲false。例如(我沒有運行這個代碼)。

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") 
+0

我不能假定它們匹配 - 在列表中的許多位置,所以我不能客串,如果它匹配 – Fangir

0

使用all聲明:

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) 
相關問題