[英]Using for loop iteration with If statement
我有多個物品的清單。 需要創建一個循環,以從列表中找到一個項目並將其打印出來。 如果未找到項目,則僅在找不到后打印一次。
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
print('wrong format')
當前,它會多次打印出找不到的內容。 當它與正則表達式匹配時,它將在末尾打印出來。 我只希望If Else打印一次“錯誤格式”。
當前打印出錯誤的格式錯誤的格式錯誤的格式錯誤的格式錯誤的格式錯誤的格式錯誤的格式錯誤的“ DeviceX正則表達式匹配”
將else
與一起for
。
當您找到一項后就退出for循環時,以下代碼將正常工作:
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
break
else:
# Does not execute only when a break statement
# is executed inside the for loop.
print('wrong format')
它被打印多次,因為在當前值不匹配的地方有很多次。 解決此問題的一種簡單方法是使用標志,如下所示:
value_found = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex,hostname):
print (dev[x],'Regex matched')
value_found = True
break
if not value_found:
print('wrong_format')
您可以按如下方式維護標志變量。
matched = False
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], "Regex matched!")
matched = True
break
if not matched:
print("Wrong format")
這應該可以解決您的問題。
flag = 0
for x in range(len(regs)):
rex = regs[x]
if re.match(rex, hostname):
print(dev[x], 'Regex matched')
flag = 1
break
if flag == 0:
print('wrong format')
我認為您可以使用以下綜合列表將其縮短:
if len([r for r in regs if re.match(r, hostname)]) == 1:
print(dev[regs.index([r for r in regs if re.match(r, hostname)][0])], 'Regex matched')
else:
print('not found')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.