Python中如何用函数实现类似or逻辑的列表首个真值提取?
or链逻辑:返回第一个真值元素 Absolutely! You can totally create a function foo that mimics the behavior of Python's or operator chain for a list. Let's break down what's happening first:
The or operator uses short-circuit evaluation: it checks each expression in order, returns the first one that's "truthy" (i.e., not a falsy value like 0, None, False, empty strings, or empty lists), and ignores everything after that. That's why your original print(0 or None or False or "" or [] or "hello" or None or "bar") outputs "hello"—it's the first truthy value in the chain.
The Simplest Implementation
For your specific example (where there's guaranteed to be at least one truthy value in the list), this one-liner function works perfectly:
def foo(lst): return next(item for item in lst if item)
Here's how it works:
- The generator expression
(item for item in lst if item)iterates through your list and only yields elements that are truthy. next()grabs the first element from this generator, which is exactly the first truthy value in your list—just like theorchain.
Testing it with your example:
print(foo([0, None, False, "", [], "hello", None, "bar"])) # Output: hello
Full or Operator Replication (Handle All Cases)
If you want to exactly match the or operator's behavior even when all elements are falsy (where or returns the last falsy value), use this version:
def foo(lst): for item in lst: if item: return item # If all items are falsy, return the last one (or None if list is empty) return lst[-1] if lst else None
This loops through each element, returns the first truthy one immediately. If it finishes the loop without finding any truthy values, it returns the last element (matching how 0 or None or False returns False), or None for an empty list.
Quick Recap of Falsy Values in Python
Just to make sure we're on the same page, these are the values Python considers falsy:
NoneFalse- Numeric zeros:
0,0.0,0j - Empty sequences/collections:
"",[],{},(),set() - Objects that implement
__bool__()returningFalseor__len__()returning0
内容的提问来源于stack exchange,提问作者oyvind

