[英]Python: How do I combine functions to one
我是python的新手。 需要幫助將以下代碼作為一個代碼塊編寫,而不是使用基於值的if語句。
for lines in f:
if 'et' in lines:
# print lines
value = re.search('(et-\d\\/\d\\/\d)', lines)
if value:
interfaces = value.group(1)
# print interfaces
smic_dict.setdefault(pfe, []).append(interfaces)
pfe_interfaces.append(interfaces)
if 'xe' in lines:
value_xe = re.search('(xe-\d\\/\d\\/\d)', lines)
if value_xe:
interfaces_xe = value_xe.group(1)
smic_dict.setdefault(pfe, []).append(interfaces_xe)
pfe_interfaces.append(interfaces_xe)
到目前為止嘗試了此:
for lines in temp:
if 'et' or 'xe' in lines:
value = re.search('(et-\d\\/\d\\/\d)', lines)
value_xe = re.search('(xe-\d\\/\d\\/\d)', lines)
if value or value_xe:
interfaces = value.group(1)
pic_interfaces.append(interfaces)
首先,這里您實際上不需要兩個if
語句。 如果該行不包含et
或xe
,則它將不匹配任何一個正則表達式,因此您可以簡化它。
其次,您的if value or value_xe:
是有意義的-但隨后您僅在下面的代碼中使用value
,而沒有使用。 您需要使用匹配的任何一個。 解決此問題的最簡單方法是只使用or
的結果。 在Python中,如果x or y
是真實的,則x or y
表示x
(在這種情況下,它表示存在匹配項,而不是None
),否則為y
。 因此,如果第一個搜索匹配,您將得到結果匹配。 如果不匹配,則第二次搜索匹配,您將得到結果匹配; 如果沒有,您將得到None
。
當我們使用它時,作為一個次要因素,從文件lines
而不是line
調用僅包含一行的變量有點令人困惑。
所以:
for line in temp:
value_et = re.search('(et-\d\\/\d\\/\d)', line)
value_xe = re.search('(xe-\d\\/\d\\/\d)', line)
value = value_et or value_xe
if value:
interfaces = value.group(1)
pic_interfaces.append(interfaces)
您可以做一些事情來進一步改善它:
\\d
表示文字反斜杠字符和d
字符有效,但這僅是因為\\d
恰巧不是Python中的轉義序列(至少從3.7開始)。 您真的不應該依賴於此。 最好做\\\\d
。 group()
而不是group(1)
。 et
或xe
,其拼寫為|
。
(?:et|xe)
。 但是,如果您只使用完整匹配,則不需要。 所以:
for line in temp:
value = re.search(r'(et|xe)-\d\/\d\/\d', line)
if value:
interfaces = value.group()
pic_interfaces.append(interfaces)
如果您將兩個正則表達式“合並”為一個,則可能也更簡潔:
for lines in f:
value = re.search('((?:et|xe)-\d\\/\d\\/\d)', lines)
if value:
interfaces = value.group(1)
# print interfaces
smic_dict.setdefault(pfe, []).append(interfaces)
pfe_interfaces.append(interfaces)
問號會創建一個所謂的“非捕獲組”,並且管道將兩種選擇組合在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.