Python 技巧 - 基础 - 第一部分

发布日期:2026-07-19 09:05:03  来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-19 09:05:03  
0

介绍

编者注:本指南是实用 Python 技巧系列的一部分。阅读有关本系列的更多信息并在此处找到其他指南的链接。

在本指南中,我们将学习 Python 中的一些基本技巧,包括最常见的高级 Python 技巧。每个 Python 技巧都分两个步骤进行解释:

  1. 概念的简要描述和交互式代码示例
  2. 一些鼓舞人心的例子来启发你

布尔表达式

a 或 b

如果a是真值,则返回a。否则,返回b

以下是官方文档中的虚假值列表:

  • 定义为 false 的常量:NoneFalse
  • 任何数字类型的零:00.00jDecimal(0)Fraction(0, 1)
  • 空序列和集合:''()[]{}set()range(0)
      a, b = 0, 42
a or b
# output: 42

a, b = '', 0
a or b
# output: 0
    

鼓舞人心的例子

在链表赋值中,如果两个候选节点中最多有一个不为None,则可以使用表达式。

      """connect with a non-empty linked list"""
cur.next = l1 or l2
    

a 和 b

如果a是假值,则返回a。否则,返回b

      a, b = 1, 2
a and b
# output: 2

a, b = '', 'abc'
a and b
# output: ''
    

鼓舞人心的例子

我们可以使用此机制在赋值之前调用函数。只需确保左表达式始终为True即可。

      """add current element to list before assignment"""
last = not arr.append(x) and arr[-1]
    

扩展知识:惰性求值

惰性求值是一种计算策略,它延迟对表达式的计算,直到需要其值为止。

这里我们讲的是惰性求值机制应用于表达式,例如a or ba and ba if condition else b。一旦语句满足条件,表达式的其余部分将被跳过。具体到下面的例子中,表达式b不会被执行。我们可以利用这种机制在表达式中进行条件执行。更多信息请参阅Python Tricks - Black Magic - Part 2指南中的“带有 break 的列表推导”示例

我们将在Python Tricks - Iterable指南中进一步讨论应用于生成器的惰性求值技术。

建立元组

为特定目的构建临时元组。用内存换取更简洁的代码。这可以扩展以构建其他集合类型。

鼓舞人心的例子

      """build in condition"""
if elem in (elem1, elem2):  # equals to: if elem == elem1 or elem == elem2

"""build result"""
return [dp[-1], -1][dp[-1] == float('inf')]		# equals to if-else, but more concise

"""build 4-neighbors as range"""
for I, J in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1):
    

布尔值

bool类型是int的子类。作为整数,True的值为1,False 的值为 0。

      int(True), int(False)
# output: (1, 0)
    

我们可以使用bool来参与运算。

鼓舞人心的例子

用于求和:计算满足条件的数量。

      """used in sum"""
equal_count = sum(a == b for a, b in zip(arr1, arr2))
    

用作索引:构造一个临时元组,并使用bool表达式作为索引。

      # L236: find the lowest common ancestor in the binary search tree
def lowest_common_ancestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    while (root.val - p.val) * (root.val - q.val) > 0:
        """used as index"""
        root = (root.left, root.right)[p.val > root.val]  # equals to if-else, seems more clearly this way
    return root
    

用于列表初始化和切片:

      # a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# L247: find all strobogrammatic numbers that are of length = n
def find_strobogrammatic(n: int) -> List[str]:
    """used in list initialization"""
    # if nums is odd, the middle digit must be in '018'
    nums = n % 2 * list('018') or ['']
    while n > 1:
        n -= 2
        """used in slice"""
        # here use to deal with number can not start with '0'
        nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
    return nums
    

三元运算符

在 C++/Java 中,可以通过内置语法条件 ? true_expression : false_expression来实现。Python 有几种自己的方法来实现这一点。各种解决方案提供了不同的思路。

本节摘自Stack Overflow 上的Python 是否有三元条件运算符?在 Python < 2.5 中执行三元条件的最佳方法。如有需要,请参考。

内置语法

这是最直接的方式,从2.5版本开始支持,表达式语法为:

      """conditional operator"""
true_expression if condition else false_expression
    

鼓舞人心的例子

我们可以使用三元运算符来查找成对或三元组中的最小/最大元素。另一种方法是使用min / max函数。

      """find maximum in pairs"""
a, b = 10, 20
max_val = a if a > b else b
# output: 20

"""find mininmum in triplets"""
a, b, c = 10, 20, 5
min_val = a if a < b and a < c else (b if b < c else c)
# output: 5
    

布尔表达式技术

对于 2.5 之前的版本,我们可以使用之前讨论过的布尔表达式技巧:

      """correct way by encapsulation with tuples"""
"""(False,) is truthy value"""
(condition and (true_expression,) or (false_expression,))[0]

"""more concise and faster way with limit"""
"""should make sure true_expression is never falsy"""
condition and true_expression or false_expression
    

然而,这种方法可能会导致某些人的可读性较差,并且速度比以前更慢。

布尔索引技术

该解决方案使用布尔值<font s

以上内容来自杭州电子商务研究院推送
分享到:

长按或扫码识别 分享给好友

长按或扫码识别 分享给好友
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据