如何解决更多 Pythonic 的 If-Else-Pass 编写方式
我有这个函数来清理我的输入表(因为我有多个表需要这种处理,所以我决定编写这个函数)。
参数'table'是我们输入的pandas DataFrame,而'control_list'只是验证我们是否要执行转换。
def input_formatting(table,control_list):
#drop rows with NA's
if control_list[0] == 1:
table.dropna(inplace = True,how = 'all')
else:
pass
#change all column names to lower case
if control_list[1] == 1:
table.columns = table.columns.str.lower()
else:
pass
#remove all whitespace in column names
if control_list[2] == 1:
table.rename(columns=lambda x: x.strip(),inplace = True)
else:
pass
#change all spaces to _ in col names
if control_list[3] == 1:
table.rename(columns=lambda x: x.replace(' ','_'),inplace = True)
else:
pass
使用它的例子是:
input_formatting(some_df,[1,1,1])
我的问题是,有人可以推荐一种更 Pythonic/优雅的方式来编写 if-else-pass 语句吗?这似乎不必要地冗长和冗长。
谢谢!
解决方法
else
在 if-else 中是可选的,即:
if True:
print("True")
else:
pass
可以用更简洁的方式写成
if True:
print("True")
help("if")
确实说
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" expression ":" suite
("elif" expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false,the suite of the "else" clause,if
present,is executed.
Related help topics: TRUTHVALUE
注意如果存在在最后一句中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。