您对这些python函数感到困惑吗

    科技2022-08-01  112

    It’s often said that one of the hardest things in programming is to name variables, which include functions as well. When some functions perform similar jobs, they naturally should have similar names, and they will inevitably bring some confusion to beginners. In this article, I’d like to review functions that have similar names but work differently.

    人们常说编程中最困难的事情之一就是为变量命名,其中还包括函数。 当某些功能执行相似的工作时,它们自然应该具有相似的名称,并且不可避免地给初学者带来一些困惑。 在本文中,我想回顾一下名称相似但功能不同的函数。

    1. sorted()vs. sort() (1. sorted() vs. sort())

    Both functions can be used to sort a list object. However, the sorted() function is a built-in function that can work with any iterable. The sort() function is actually a list’s method, which means that it can only be used with a list object. They also have different syntax.

    这两个函数都可以用于对列表对象进行排序。 但是, sorted()函数是一个内置函数,可以与任何可迭代对象一起使用。 sort()函数实际上是列表的方法,这意味着它只能与列表对象一起使用。 它们还具有不同的语法。

    >>> # sorted() for any iterable >>> sorted([7, 4, 3, 2], reverse=True) [7, 4, 3, 2] >>> sorted({7: 'seven', 2: 'two'}) [2, 7] >>> sorted([('nine', 9), ('one', 1)], key=lambda x: x[-1]) [('one', 1), ('nine', 9)] >>> sorted('hello') ['e', 'h', 'l', 'l', 'o'] >>> >>> # sort() for a list >>> grades = [{'name': 'John', 'grade': 99}, ... {'name': 'Mary', 'grade': 95}, ... {'name': 'Zack', 'grade': 97}] >>> grades.sort(key=lambda x: x['grade'], reverse=True) >>> grades [{'name': 'John', 'grade': 99}, {'name': 'Zack', 'grade': 97}, {'name': 'Mary', 'grade': 95}]

    Both functions have the arguments reverse and key. The reverse argument is to request the sorting in reverse order, while the key argument is to specify the sorting algorithm beyond the default order. It can be set as a lambda function or a regular function.

    这两个函数都具有参数reverse和key 。 reverse参数要求以相反的顺序进行排序,而key参数则要指定超出默认顺序的排序算法。 可以将其设置为lambda函数或常规函数。

    The sorted() function can work with any iterable. In the case of the dictionary (Line 4), the iterable from a dictionary object is the keys, and thus the sorted() function returns a list object of the keys.

    sorted()函数可以与任何可迭代对象一起使用。 对于字典(第4行),可从字典对象进行迭代的是键,因此sorted()函数将返回键的列表对象。

    In a similar fashion, when you pass a string to the sorted() function, it will return a list of characters because a string is treated as an iterable consisting of individual characters.

    以类似的方式,当您将字符串传递给sorted()函数时,它将返回字符列表,因为字符串被视为由单个字符组成的可迭代。

    The sorted() function returns a list object in the sorted order, while the sort() function doesn’t return anything (or returns None, to be precise). In other words, the list object calling the sort() function is to be sorted in place.

    sorted()函数以排序顺序返回列表对象,而sort()函数不返回任何内容(或者精确地返回None )。 换句话说,调用sort()函数的列表对象将在适当位置进行排序。

    2. reversed()vs. reverse() (2. reversed() vs. reverse())

    The use scenarios for these two are similar to sorted() vs. sort(). The reversed() function works with any sequence data, such as lists and strings, while the reverse() function is a list’s method.

    这两个的使用场景类似于sorted() vs. sort() 。 reversed()函数可用于任何序列数据,例如列表和字符串,而reverse()函数是列表的方法。

    >>> # reversed() for any sequence data >>> reversed([1, 2, 3]) <list_reverseiterator object at 0x11b035490> >>> list(reversed((1, 2, 3))) [3, 2, 1] >>> tuple(reversed('hello')) ('o', 'l', 'l', 'e', 'h') >>> >>> # reverse() for a list >>> numbers = [1, 2, 3, 4] >>> numbers.reverse() >>> numbers [4, 3, 2, 1]

    Unlike the sorted() function, which returns a list, the reversed() function returns a reverse iterator, which is essentially an iterable but can be directly used in the for loop.

    与sorted()函数返回一个列表不同, reversed()函数返回一个反向迭代器,该迭代器本质上是可迭代的,但可以直接在for循环中使用。

    To construct a list or a tuple, you can utilize the returned iterator to construct a sequence data in the reverse order from the original one.

    要构造列表或元组,可以利用返回的迭代器以与原始顺序相反的顺序构造序列数据。

    As with the sort() method on a list, the reverse() method is to reverse the order of the list’s elements in place, and thus it returns None.

    与列表上的sort()方法一样, reverse()方法是将列表中元素的顺序颠倒过来,因此它返回None 。

    3. append()vs.extend() (3. append() vs. extend())

    Both of these functions are list objects’ methods. Both are used to add items to an exiting list object. The following code shows you how to use them and is followed by some explanations.

    这两个函数都是列表对象的方法。 两者都用于将项目添加到现有列表对象。 以下代码显示了如何使用它们,并附有一些说明。

    >>> # Create a list object to begin with >>> integers = [1, 2, 3] >>> >>> # append() >>> integers.append(4) >>> integers.append([5, 6]) >>> integers [1, 2, 3, 4, [5, 6]] >>> >>> # extend() >>> integers.extend({7, 8, 9}) >>> integers.extend('hello') >>> integers [1, 2, 3, 4, [5, 6], 8, 9, 7, 'h', 'e', 'l', 'l', 'o']

    Both functions modify the list object in place and return None.

    这两个函数都会修改列表对象,并返回None 。

    The append() function is to append a single item to the end of the list. If you want to add an item to a specific location, you should use the insert() method.

    append()函数用于将单个项目追加到列表的末尾。 如果要将项目添加到特定位置,则应使用insert()方法。

    The extend() function is to append all the elements in an iterable to the end of the list object. In the case of the string (Line 12), the characters are appended. For the set object, you notice that the order of the elements inserted doesn’t reflect the items that we use to create the set object, which is the expected behavior of a set object that holds unordered items.

    extend()函数用于将可迭代的所有元素附加到列表对象的末尾。 对于字符串(第12行),将附加字符。 对于set对象,您会注意到插入元素的顺序并不反映我们用于创建set对象的项目,这是保存无序项目的set对象的预期行为。

    4.是vs. == (4. is vs. ==)

    Both functions are used to compare objects. However, they have some nuances that you should be aware of. We refer to is as the identity comparison and == as the value equality comparison. One thing to note is that when we say the identity of an object, we can simply refer to the memory address of a particular object using the id() function. Let’s see some examples.

    这两个函数都用于比较对象。 但是,它们有一些细微差别,您应该注意。 我们称为is 身份比较 , ==称为值相等比较 。 需要注意的一件事是,当我们说一个对象的身份时,我们可以使用id()函数简单地引用一个特定对象的内存地址。 让我们看一些例子。

    >>> # Create a function for comparison >>> def compare_two_objects(obj0, obj1): ... print("obj0 id:", id(obj0), "obj1 id:", id(obj1)) ... print("Compare Identity:", obj0 is obj1) ... print("Compare Value:", obj0 == obj1) ... >>> compare_two_objects([1, 2, 3], [1, 2, 3]) obj0 id: 4749717568 obj1 id: 4748799936 Compare Identity: False Compare Value: True >>> compare_two_objects([1, 2].reverse(), None) obj0 id: 4465453816 obj1 id: 4465453816 Compare Identity: True Compare Value: True

    When the objects have the same memory address, they’re the same objects and have the same identity and value. Thus, is and == produce the same boolean value.

    当对象具有相同的内存地址时,它们就是相同的对象,并且具有相同的标识和值。 因此, is和==产生相同的布尔值。

    In most cases, even objects can have the same values, but they can be different objects in the memory.

    在大多数情况下,即使对象可以具有相同的值,但它们可以是内存中的不同对象。

    Some special objects, such as None and small integers (e.g., 1, 2) always have the same identity because they’re used so much and have already been instantiated when Python was loaded. We share these objects between different modules.

    一些特殊对象(例如None和小整数(例如1、2))始终具有相同的标识,因为它们已被大量使用并且在加载Python时已被实例化。 我们在不同模块之间共享这些对象。

    In most cases, we use == to compare objects because we’re mostly interested in using the values of the objects. However, we do prefer using is when we examine if an object is None or not (i.e., if obj is None).

    在大多数情况下,我们使用==来比较对象,因为我们最感兴趣的是使用对象的值。 但是,当检查对象是否为None (即if obj is None ),我们确实更喜欢使用is 。

    5. remove(),pop()与clear() (5. remove(), pop() vs. clear())

    These three functions are list objects’ methods, which is confusing. Let’s see their usages first, and we’ll discuss their nuances next.

    这三个函数是列表对象的方法,这很令人困惑。 首先让我们看看它们的用法,然后我们将讨论它们的细微差别。

    >>> # Create a list of integers >>> integers = [1, 2, 3, 4, 5] >>> >>> # remove() >>> integers.remove(1) >>> integers [2, 3, 4, 5] >>> >>> # pop() >>> integers.pop() 5 >>> integers [2, 3, 4] >>> integers.pop(0) 2 >>> integers [3, 4] >>> >>> # clear() >>> integers.clear() >>> integers []

    To remove a particular item, you can specify it in the remove() function. But be cautious. If the item that is to be removed isn’t in the list, you’ll encounter a ValueError exception, as shown below.

    要删除特定项目,可以在remove()函数中指定它。 但是要小心。 如果要删除的项目不在列表中,则将遇到ValueError异常,如下所示。

    >>> [1, 2, 3, 4].remove(5)Traceback (most recent call last): File "<input>", line 1, in <module>ValueError: list.remove(x): x not in list

    The pop() method is removing the last item by default. If you want to remove an element at a specific index, you can specify it in the function, as shown in Line 14. Importantly, this method will return the popped item, and thus it’s particularly useful if you want to work with the removed item. One thing to note is that this method will raise an IndexError if the list has become empty.

    pop()方法默认删除最后一个项目。 如果要删除特定索引处的元素,则可以在函数中指定它,如第14行所示。重要的是,此方法将返回弹出的项目,因此,如果要使用删除的项目,该方法特别有用。 。 要注意的一件事是,如果列表已为空,则此方法将引发IndexError 。

    >>> [].pop()Traceback (most recent call last): File "<input>", line 1, in <module>IndexError: pop from empty list

    The clear() method is to remove all items in the list, which should be straightforward.

    clear()方法是删除列表中的所有项目,这应该很简单。

    6. any()与all() (6. any() vs. all())

    Both functions are used to check conditions using iterables. The returned value for both functions are boolean values — True or False. The following code shows you some usages.

    这两个函数都用于检查使用迭代器的条件。 这两个函数的返回值都是布尔值True或False 。 以下代码向您展示了一些用法。

    >>> # Create a function to check iterables >>> def check_any_all(iterable): ... print(f"any({iterable!r}): {any(iterable)}") ... print(f"all({iterable!r}): {all(iterable)}") ... >>> >>> check_any_all([1, False, 2]) any([1, False, 2]): True all([1, False, 2]): False >>> check_any_all([True, True, True]) any([True, True, True]): True all([True, True, True]): True >>> check_any_all(tuple()) any(()): False all(()): True

    When any item in the iterable is True, any() returns True. Otherwise, it returns False.

    当iterable中的任何一项为True , any()返回True 。 否则,它返回False 。

    Only when all the items in the iterable are True does all() return True. Otherwise, it returns False.

    只有当iterable中的所有项目均为True , all()才会返回True 。 否则,它返回False 。

    Special consideration is given when the iterable is empty. As you can see, any() returns False, while all() returns True. Many people are confused by this behavior. This is how you can remember that: By default, any() returns False. Only can it find a non-False item, it will return True immediately — a short-circuit evaluation. By contrast, all() returns True by default. Only can it find a non-True item, it will return False immediately — again, a short-circuit evaluation.

    当iterable为空时,将给予特殊考虑。 如您所见, any()返回False ,而all()返回True 。 许多人对此行为感到困惑。 这样可以记住:默认情况下, any()返回False 。 它只能找到一个非False项目,它会立即返回True短路评估。 相比之下, all()默认情况下返回True 。 它只能找到一个非True项,它将立即返回False再次是短路评估。

    7. issuperset()与issubset() (7. issuperset() vs. issubset())

    We have talked about several methods related to lists. In terms of set objects, the one pair of methods that I find confusing is issuperset() and issubset(). Let’s first see how they work with some trivial examples.

    我们已经讨论了几种与列表相关的方法。 就集合对象而言,我发现令人困惑的一对方法是issuperset()和issubset() 。 首先让我们看一下它们如何与一些琐碎的示例一起工作。

    >>> # Create a function to check set relationship >>> def check_set_relation(set0, set1): ... print(f"Is {set0} a superset of {set1}?", set0.issuperset(set1)) ... print(f"Is {set0} a subset of {set1}?", set0.issubset(set1)) ... >>> check_set_relation({1, 2, 3}, {2, 3}) Is {1, 2, 3} a superset of {2, 3}? True Is {1, 2, 3} a subset of {2, 3}? False >>> check_set_relation({3, 4}, {3, 4, 5}) Is {3, 4} a superset of {3, 4, 5}? False Is {3, 4} a subset of {3, 4, 5}? True Both methods are used to check the relationship between two set objects.

    两种方法都用于检查两个集合对象之间的关系。

    The key distinction to understand these methods is that the caller of the method is to be checked against the input argument. For instance, set0.issuperset(set1) is to check whether set0 is a superset of set1.

    理解这些方法的主要区别在于,将根据输入参数检查方法的调用者。 例如, set0.issuperset(set1)将检查set0是否为set1的超集。

    8. zip()与zip_longest() (8. zip() vs. zip_longest())

    The zip() function is a built-in function that is used to create a zip object that can be used in a for loop. It takes multiple iterables and creates a generator that yields a tuple object each time. Each tuple object consists of elements from each iterable at the corresponding position. The zip_longest() works similarly, but has some differences.

    zip()函数是一个内置函数,用于创建可在for循环中使用的zip对象。 它需要多个可迭代对象,并创建一个生成器,每次生成一个元组对象。 每个元组对象都包含来自每个可迭代元素的对应位置。 zip_longest()工作原理类似,但有一些区别。

    >>> # Create two lists for zipping >>> list0 = [1, 2, 3] >>> list1 = ['a', 'b', 'c', 'd', 'e'] >>> >>> # Zip two lists with zip() >>> zipped0 = list(zip(list0, list1)) >>> zipped0 [(1, 'a'), (2, 'b'), (3, 'c')] >>> >>> # Zip two lists with zip_longest() >>> from itertools import zip_longest >>> zipped1 = list(zip_longest(list0, list1)) >>> zipped1 [(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd'), (None, 'e')] To create a list of the zip object, you’ll include the zip object in the list constructor method, as shown in Line 6.

    要创建zip对象的列表,请将zip对象包含在list构造函数方法中,如第6行所示。

    The zip() function will create the tuples with the number that matches the length of the shortest iterable. In our example, it only creates three tuples because the shorter list (i.e., list0) only has three items.

    zip()函数将创建具有与最短可迭代长度匹配的数字的元组。 在我们的示例中,它仅创建三个元组,因为较短的列表(即list0 )只有三个项目。

    By contrast, with the zip_longest() function, the number of created tuples will match the length of the longest iterable. For the shorter iterables, the tuples will use None instead.

    相比之下,使用zip_longest()函数,创建的元组的数量将与最长可迭代的长度匹配。 对于较短的可迭代对象,元组将使用None代替。

    结论 (Conclusions)

    In this article, we reviewed eight groups of functions with similar functionalities that can be somewhat confusing to some Python beginners.

    在本文中,我们回顾了八组具有相似功能的函数,这些功能可能会使某些Python初学者感到困惑。

    Thanks for reading this piece.

    感谢您阅读本文。

    翻译自: https://medium.com/better-programming/are-you-confused-by-these-python-functions-8e9e7f3d7605

    相关资源:微信小程序源码-合集6.rar
    Processed: 0.012, SQL: 8