How to fix multiple if codes in python

Question:

My python code is ugly.
How to tune this code?

find_list1 = re.findall(p1, path)
find_list2 = re.findall(p2, path)
find_list3 = re.findall(p3, path)
if len(find_list1) > 0:find_list = find_list1
if len(find_list2) > 0:find_list = find_list2
if len(find_list3) > 0:find_list = find_list3
if len(re.findall(p1, path)) > 0:date_str1 += re.findall(p1, path)[0] + " " 
if len(re.findall(p2, path)) > 0:date_str2 += re.findall(p2, path)[0] + " " 
if len(re.findall(p3, path)) > 0:date_str3 += re.findall(p3, path)[0] + " " 
if len(date_str1) > 0:date_str = date_str1
if len(date_str2) > 0:date_str = date_str2
if len(date_str3) > 0:date_str = date_str3

Thank you.

Asked By: fleamon

||

Answers:

Without knowing if/how these intermediate variables are used it’s difficult to be optimal.

Assuming that find_list, date_str, date_str1, date_str2 and date_str3 had previous content, and that find_list1, find_list2 and find_list3 are used later, the code could be written as follows to make it a bit more compact and avoid re-computing values already obtained on previous lines.

find_list1 = re.findall(p1, path)
find_list2 = re.findall(p2, path)
find_list3 = re.findall(p3, path)
if find_list1: date_str1 += find_list1[0] + " "
if find_list2: date_str2 += find_list2[0] + " "
if find_list3: date_str3 += find_list3[0] + " "
find_list = find_list3 or find_list2 or find_list1 or find_list
date_str  = date_str3  or date_str2  or date_str1  or date_str

The use of or leverages short-circuiting and Python’s implicit "truthy" value of lists (an empty list is False, a non-empty list is True). So doing A = B or C for lists assigns B if it is not empty (which short circuits the or). If B is empty (False) then or proceeds to the next operand and returns C. The one-line assignments to find_list and date_str produce the same result as the series of if statements (the order of operands is important though)

Answered By: Alain T.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.