简体   繁体   English

Python - 在条件上调用函数

[英]Python - Call a Function on a Condition

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. 它不起作用。

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. 但是,这既不简洁也不可读。

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. 因此,您不能使用已使用的pass和normal if语句是正确的。

Using pass seems like a bad idea in a ternary operator, especially since you can inline a single-statement if . 在三元运算符中使用pass似乎是一个坏主意,特别是因为你可以内联单个语句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. 如果您不担心列表为None ,则可以将测试缩短为仅使用列表本身的布尔值。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM