Python - Call a Function on a Condition

蓝咒 提交于 2020-01-14 14:47:08

问题


I was wondering if there is a concise way to call a function on a condition.

I have this:

if list_1 != []:
    some_dataframe_df = myfunction()

I'm wondering if it is possible to this in a ternary operator or something similiar.

If I do

(some_dataframe_df = myfunction()) if list_1 != [] else pass

It doesn't work.


回答1:


Your code is fine. The only change I suggest is to use the inherent Truthness of non-empty lists:

if list_1:
    some_dataframe_df = myfunction()

If you wish to use a ternary statement it would be written as:

some_dataframe_df = myfunction() if list_1 else some_dataframe_df

However, this is neither succinct nor readable.




回答2:


In ternary operator, the conditionals are an expression, not a statement. Therefore, you can not use pass and normal if statement that you have used is correct.




回答3:


Using pass seems like a bad idea in a ternary operator, especially since you can inline a single-statement if.

If you are not worried about your list being None, you can shorten the test to just use the boolean value of the list itself. This has the advantage that it will allow any normal sequence, not just lists.

All in all, you could do something like:

if list_1: some_dataframe_df = myfunction()


来源:https://stackoverflow.com/questions/53229230/python-call-a-function-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!