我有以下代码可以很好地工作,并且可以给我预期的结果,但是我知道有一种方法可以简化它,我认为使以下代码最好的方法不是3/4行20个左右。 Python专家需要您的建议,我如何简化以下代码。
for ele in hng_row:
if not ele.isdigit():
if not ele.isalpha():
if not ele.isalnum():
if ele.endswith('.00'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if ele.startswith('0.') and ele.endswith('0') and ele != '0.0':
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if (ele[-2] != '0' ) and (ele[-2] != '.') and (ele[-1] == '0'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
答案 0 :(得分:2)
第一步:合并条件(+ pylint)
Shifts = new BindingList<Shift> ();
foreach (DataRow row in shifts.Rows)
{
Shifts.Add(new Shift { Value = row["value"].ToString(), ID = Convert.ToInt16(row["id_value"]), Color = row["color"].ToString() });
}
第二步:重构if块
for ele in hng_row:
if not ele.isdigit() and not ele.isalpha() and not ele.isalnum():
if ele.endswith('.00'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if ele.startswith('0.') and ele.endswith('0') and ele != '0.0':
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if (ele[-2] != '0') and (ele[-2] != '.') and (ele[-1] == '0'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
答案 1 :(得分:2)
可以进一步简化(或者说“缩短”)。首先,请注意,检查not isdigit
,not isalpha
和not isalnum
是多余的,您只需要检查not isalnum
。其次,您可以使用regular expression来检查数字格式,并将三个条件与|
结合在一起。另外,您可以enumerate
项,而不用获取index
。
for index, ele in enumerate(hng_row):
if not ele.isalnum() and re.match(r"^.*\.00|0\..+0|.*[^0.]0$", ele):
hng_row[index] = ele[:-1]
在这里,正则表达式为^.*\.00|0\..+0|.*[^0.]0$
。 ^
标记字符串的开头,$
结束,|
表示析取,即字符串必须与.*\.00
匹配(后跟.00
)或0\..+0
(0.
,然后是某些内容,然后是0
)或.*[^0.]0
(后跟0
和.
,然后是{{1 }}。
您还可以用列表理解替换循环:
0
答案 2 :(得分:0)
前几条if语句可以排成一行。
for ele in hng_row:
if not ele.isdigit() and not ele.isalpha() and not ele.isalnum():
if ele.endswith('.00'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if ele.startswith('0.') and ele.endswith('0') and ele != '0.0':
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele
if (ele[-2] != '0' ) and (ele[-2] != '.') and (ele[-1] == '0'):
get_index = hng_row.index(ele)
ele = ele[:-1]
hng_row[get_index] = ele