zoukankan      html  css  js  c++  java
  • python3 之初学者常犯的5个错误

    1. Creating a copy of dictionary or lists.

    Whenever you need to make a copy of a dictionary or list, do not simply use the assignment operator.

    Right way: Use the copy()  or deepcopy()  method. 

    2. Dictionary keys.

    Remember Boolean class is the subclass of Integer. Integer equivalent of True is 1 and that of False is 0. Hence value of key 1 is overwritten

    3. Updating lists or dictionaries.

     Most the sequence object methods like sort, update, append, add etc works in place to increase performance by avoiding to create a separate copy un-necessarily.

    Do not try to assign the output of such methods to variable. 

    In some cases, python try to reuse the existing immutable objects. String interning is one such case

    >>> a = "gmail"
    >>> b = "gmail"
    >>> a is b
    True

     All strings of length 1 are interned. String having anything except ASCII characters, digits and underscore in them are not interned.

    Let's see. 

    >>> a = "@gmail"
    >>> b = "@gmail"
    >>> a is b
    False
    Also remember ==  is different than is  operator. ==  checks if values are equal or not while is  checks if both variable are pointing to same object. 

    5. Default arguments are evaluated only once.

    Consider below example.

    def func(a, lst=[]):
        lst.append(a)
        return lst
    
    print(func(1))
    print(func(2))

    What do you think will be the output of above two print statements?

    Lets try to run it.

    >>> def func(a, lst=[]):
    ...     lst.append(a)
    ...     return lst
    ... 
    >>> print(func(1))
    [1]
    >>> print(func(2))
    [1, 2]

     

  • 相关阅读:
    Kruskal
    克鲁斯卡尔
    克鲁斯卡尔
    实践是检验真理的唯一标准 脱壳篇02
    Kruskal
    克鲁斯卡尔算法讲解
    实践是检验真理的唯一标准 脱壳篇02
    最小生成树(普里姆算法) 数据结构和算法62
    克鲁斯卡尔算法讲解
    最小生成树(普里姆算法) 数据结构和算法62
  • 原文地址:https://www.cnblogs.com/zxpo/p/10011173.html
Copyright © 2011-2022 走看看