微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更多 Pythonic 的 If-Else-Pass 编写方式

如何解决更多 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?