vs调试技巧和诀窍系列

    科技2026-08-19  8

    vs调试技巧和诀窍系列

    上下文管理器,拆箱,随机 (Context Managers, Unpacking, Random)

    #1上下文管理器 (#1 Context Managers)

    The context managers allow to allocate and release resources precisely when a program wants to get access to a resource on the computer. It asks the OS for it and the OS provides it with a handle for that resource requested. Some common examples of such resources are files and network ports. Whenever we open a resource, we have to remember to close it, so that the resource is freed. But unfortunately, it’s easier said than done in the program. The with statement is a widely used example of context managers.

    当程序想要访问计算机上的资源时,上下文管理器允许精确地分配和释放资源。 它向OS询问,并且OS为它提供所请求资源的句柄。 此类资源的一些常见示例是文件和网络端口。 每当我们打开资源时,我们都必须记住要关闭它,以便释放资源。 但是不幸的是,说起来容易做起来难。 with语句是上下文管理器的一个广泛使用的示例。

    --------------------------------------------------------------# Manually managing the resourcesf = open('test.txt','r')file = f.read()f.close()--------------------------------------------------------------# Using with statement to manage the resources automaticallywith open('test.txt','r') as f: file = f.read()--------------------------------------------------------------

    This context managers can also be used in threads where we are manually acquiring and releasing locks, opening and closing the database connections manually so that the OS manages automatically for us.

    该上下文管理器也可以在我们手动获取和释放锁,手动打开和关闭数据库连接的线程中使用,以便操作系统为我们自动管理。

    数字文字中的#2下划线 (#2 Underscores in Numeric Literals)

    Python’s syntax and number-from-string constructors so that underscores can be used as visual separators for digit grouping purposes in integral, floating-point, and complex number literals.

    Python的语法和从字符串开始的数字构造函数,因此下划线可用作整数,浮点数和复数数字文字中数字分组目的的可视分隔符。

    This is a common feature of other modern languages and can aid readability of long literals, or literals whose value should clearly separate into parts, such as bytes or words in hexadecimal notation.

    这是其他现代语言的共同特征,可以帮助较长的文字(或其值应清楚地分成几部分的文字)(例如字节或十六进制表示的单词)的可读性。

    # grouping decimal numbers by thousandsamount = 10_000_000.0# grouping hexadecimal addresses by wordsaddr = 0xCAFE_F00D# grouping bits into nibbles in a binary literalflags = 0b_0011_1111_0100_1110# same, for string conversionsflags = int('0b_1111_0000', 2)

    #3打开一个元组/列表的包装 (#3 Unpack a tuple / list)

    In Python, elements of tuples and lists can be assigned to multiple variables. It is called sequence unpacking.

    在Python中,元组和列表的元素可以分配给多个变量。 这称为序列拆包。

    t = (0, 1, 2)a, b, c = tprint(a)print(b)print(c)# 0# 1# 2l = [0, 1, 2]a, b, c = lprint(a)print(b)print(c)# 0# 1# 2

    Because parentheses of tuples can be omitted, multiple values can be assigned to multiple variables in one line as follows.

    因为可以省略元组的括号,所以可以在一行中将多个值分配给多个变量,如下所示。

    a, b = 0, 1print(a)print(b)# 0# 1

    #4解开嵌套的元组和列表 (#4 Unpack a nested tuple and list)

    We can also unpack a nested tuple and list. To expand the inner element, enclose the variable with () or [].

    我们还可以解压缩嵌套的元组和列表。 要扩展内部元素,请用()或[]包围变量。

    t = (0, 1, (2, 3, 4))a, b, c = tprint(a)print(b)print(c)# 0# 1# (2, 3, 4)print(type(c))# <class 'tuple'>a, b, (c, d, e) = tprint(a)print(b)print(c)print(d)print(e)# 0# 1# 2# 3# 4

    #5使用_ (下划线)解压缩 (#5 Unpack using _ (underscore))

    By convention, unnecessary values may be assigned to underscores _ in Python. It does not have a grammatical special meaning but is simply assigned to a variable named _.

    按照约定,可以在Python中将不必要的值分配给下划线_ 。 它没有语法上的特殊含义,只是分配给名为_的变量。

    t = (0, 1, 2)a, b, _ = tprint(a)print(b)print(_)# 0# 1# 2

    #6使用* (星号)解压缩 (#6 Unpack using * (asterisk))

    If the number of variables is less than the number of elements, adding an asterisk * to the variable name will assign the elements together as a list.

    如果变量的数量少于元素的数量,则在变量名称上添加星号*会将元素一起分配为列表。

    It is implemented in Python 3 and can not be used in Python 2.

    它是在Python 3中实现的,不能在Python 2中使用。

    The elements from the beginning and the end are assigned to variables without *, and the remaining elements are assigned as a list of variables with *.

    从头到尾的元素被分配给不带*变量,其余元素被分配为带有*的变量列表。

    t = (0, 1, 2, 3, 4)a, b, *c = tprint(a)print(b)print(c)# 0# 1# [2, 3, 4]print(type(c))# <class 'list'>a, *b, c = tprint(a)print(b)print(c)# 0# [1, 2, 3]# 4*a, b, c = tprint(a)print(b)print(c)# [0, 1, 2]# 3# 4

    For example, when it is desired to assign only the first two elements of a tuple or a list to variables, the underscore _ may be used for unnecessary parts.

    例如,当希望仅将元组或列表的前两个元素分配给变量时,下划线_可以用于不必要的部分。

    a, b, *_ = tprint(a)print(b)print(_)# 0# 1# [2, 3, 4]

    The same process can be written as:

    相同的过程可以写成:

    a, b = t[0], t[1]print(a)print(b)# 0# 1

    Note that even if there is only one element assigned to a variable with *, it is assigned as a list.

    请注意,即使只有一个用*分配给变量的元素,也将其分配为列表。

    t = (0, 1, 2)a, b, *c = tprint(a)print(b)print(c)# 0# 1# [2]print(type(c))# <class 'list'>

    If there are no extra elements, an empty list is assigned.

    如果没有多余的元素,则会分配一个空列表。

    a, b, c, *d = tprint(a)print(b)print(c)print(d)# 0# 1# 2# []

    #7同时使用enumerate()和zip() (#7 Use enumerate() and zip() at the same time)

    In Python, enumerate() and zip() are useful when iterating elements such as lists in a for a loop. We can get the index with the enumerate() method, and get the elements of multiple lists together with zip() method.

    在Python中,当迭代for循环中的列表之类的元素时, enumerate()和zip()很有用。 我们可以使用enumerate()方法获取索引,并使用zip()方法获取多个列表的元素。

    If you want to get the elements of multiple lists and indexes, you can use enumerate() and zip() at the same time.

    如果要获取多个列表和索引的元素,则可以同时使用enumerate()和zip() 。

    In this case, you need to enclose the elements of zip() in parentheses, like for i, (a, b, ...) in enumerate(zip( ... )).

    在这种情况下,您需要将zip()的元素括在括号中,例如for i, (a, b, ...) in enumerate(zip( ... ))括for i, (a, b, ...) in enumerate(zip( ... )) 。

    names = ['Alice', 'Bob', 'Charlie']ages = [24, 50, 18]for i, (name, age) in enumerate(zip(names, ages)): print(i, name, age)# 0 Alice 24# 1 Bob 50# 2 Charlie 18

    We can also receive the elements of zip() as a tuple.

    我们还可以将zip()的元素作为元组接收。

    ---------------------------------------------------------------for i, t in enumerate(zip(names, ages)): print(i, t)# 0 ('Alice', 24)# 1 ('Bob', 50)# 2 ('Charlie', 18)---------------------------------------------------------------for i, t in enumerate(zip(names, ages)): print(i, t[0], t[1])# 0 Alice 24# 1 Bob 50# 2 Charlie 18---------------------------------------------------------------

    #8使用divmod()方法获得商和余数 (#8 Get quotient and remainder with divmod() method)

    We can calculate the quotient with // and the remainder with %.

    我们可以用//计算商,用%计算余数。

    q = 10 // 3mod = 10 % 3print(q, mod)# 3 1

    The built-in function divmod() is useful when you want both the quotient and the remainder.

    当需要商和余数时,内置函数divmod()很有用。

    divmod(a, b) returns a tuple (a // b, a % b).

    divmod(a, b)返回一个元组(a // b, a % b) 。

    Each can be assigned to a variable using unpacking.

    可以使用解包将每个变量分配给一个变量。

    ---------------------------------------------------------------q, mod = divmod(10, 3)print(q, mod)# 3 1---------------------------------------------------------------answer = divmod(10, 3)print(answer)print(answer[0], answer[1])# (3, 1)# 3 1---------------------------------------------------------------

    #9 random.shuffle()播放原始列表 (#9 random.shuffle() shuffles the original list)

    The original list can be shuffled in place by using random.shuffle().

    原始列表可以通过使用random.shuffle()进行混洗。

    import randoml = list(range(5))print(l)# [0, 1, 2, 3, 4]random.shuffle(l)print(l)# [4, 3, 2, 1, 0]

    #10 random.sample()返回一个新的#10 random.sample()列表 (#10 random.sample() returns a new shuffled list)

    random.sample() returns a new shuffled list. The original list remains unchanged.

    random.sample()返回一个新的random.sample()列表。 原始列表保持不变。

    random.sample() returns random elements from a list. Pass the list to the first argument and the number of elements to return to the second argument. See the following post for details.

    random.sample()返回列表中的随机元素。 将列表传递给第一个参数,并将元素数传递给第二个参数。 有关详细信息,请参见以下帖子。

    l = list(range(5))print(l)# [0, 1, 2, 3, 4]lr = random.sample(l, len(l))print(lr)# [3, 2, 4, 1, 0]print(l)# [0, 1, 2, 3, 4]

    #11随机播放字符串和元组 (#11 Shuffle strings and tuples)

    To shuffle strings or tuples, use random.sample() which creates a new object.

    要随机播放字符串或元组,请使用random.sample()创建一个新对象。

    random.sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

    即使第一个参数指定了字符串或元组, random.sample()也会返回一个列表,因此有必要将其转换为字符串或元组。

    For strings, a list of characters is returned. Use the join() method to concatenate to a single string again.

    对于字符串,将返回字符列表。 使用join()方法再次连接到单个字符串。

    sr = ''.join(random.sample(s, len(s)))print(sr)# caebd

    For tuples, use tuple(), which creates a tuple from a list.

    对于元组,请使用tuple()从列表中创建一个元组。

    tr = tuple(random.sample(t, len(l)))print(tr)# (2, 1, 4, 3, 0)

    #12播下种子 (#12 Set a seed)

    By giving an arbitrary integer to random.seed(), the seed for generating random numbers can be set.

    通过为random.seed()提供任意整数,可以设置用于生成随机数的种子。

    random.seed(0)l = list(range(5))random.shuffle(l)print(l)# [2, 1, 0, 4, 3]

    Please find more Python tricks for working with strings below.

    请在下面找到更多处理字符串的Python技巧。

    进一步阅读 (Further Reading)

    PEP 515 — Underscores in Numeric Literals

    PEP 515 —数字文字的下划线

    Built-in Functions — divmod() — Python 3.7.4 documentation

    内置函数— divmod()— Python 3.7.4文档

    random — Generate pseudo-random numbers — Python 3.8.1 documentation

    random —生成伪随机数— Python 3.8.1文档

    “All software boils down to pure binary. It works or it doesn’t.”

    “所有软件都可以归结为纯二进制文件。 它行不通。”

    翻译自: https://medium.com/analytics-vidhya/interesting-python-tips-and-tricks-6d033967b5a5

    vs调试技巧和诀窍系列

    相关资源:四史答题软件安装包exe
    Processed: 0.011, SQL: 9