入门知识拾遗

一、作用域

对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用。

1
2
3
if 1==1:
    name = 'wupeiqi'
print  name

下面的结论对吗?

外层变量,可以被内层变量使用

内层变量,无法被外层变量使用

二、三元运算

1
result = 1 if 条件 else 2

如果条件为真:result = 值1
如果条件为假:result = 值2

三、进制

  • 二进制,01

  • 八进制,01234567

  • 十进制,0123456789

  • 十六进制,0123456789ABCDE

Python基础

对于Python,一切事物都是对象,对象基于类创建

Python基础(一)_二进制

所以,以下这些值都是对象: "wupeiqi"、38、['北京', '上海', '深圳'],并且是根据不同的类生成的对象。

Python基础(一)_二进制_02Python基础(一)_十六进制_03Python基础(一)_八进制_04

一、整数

如: 18、73、84

每一个整数都具备如下功能:

Python基础(一)_result_05int

二、长整型

可能如:2147483649、9223372036854775807

每个长整型都具备如下功能:

Python基础(一)_十进制_06long

三、浮点型

如:3.14、2.88

每个浮点型都具备如下功能:

Python基础(一)_result_07float

四、字符串

如:'wupeiqi'、'alex'

每个字符串都具备如下功能:

Python基础(一)_十六进制_08str

注:编码;字符串的乘法;字符串和格式化

五、列表

如:[11,22,33]、['wupeiqi', 'alex']

每个列表都具备如下功能:

Python基础(一)_八进制_09list

注:排序;

六、元组

如:(11,22,33)、('wupeiqi', 'alex')

每个元组都具备如下功能:

Python基础(一)_十六进制_10tuple

七、字典

如:{'name': 'wupeiqi', 'age': 18} 、{'host': '2.2.2.2', 'port': 80]}

ps:循环时,默认循环key

每个字典都具备如下功能:

Python基础(一)_二进制_11dict

1
2
3
练习:元素分类
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}

 八、set集合

set是一个无序且不重复的元素集合

Python基础(一)_二进制_12

class set(object):    """
    set() -> new empty set object
    set(iterable) -> new set object
    
    Build an unordered collection of unique elements.    """
    def add(self, *args, **kwargs): # real signature unknown
        """ 添加 """
        """
        Add an element to a set.
        
        This has no effect if the element is already present.        """
        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        pass

    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set.
        
        (i.e. all elements that are in this set but not the others.)        """
        pass

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ 删除当前set中的所有包含在 new set 里的元素 """
        """ Remove all elements of another set from this set. """
        pass

    def discard(self, *args, **kwargs): # real signature unknown
        """ 移除元素 """
        """
        Remove an element from a set if it is a member.
        
        If the element is not a member, do nothing.        """
        pass

    def intersection(self, *args, **kwargs): # real signature unknown
        """ 取交集,新创建一个set """
        """
        Return the intersection of two or more sets as a new set.
        
        (i.e. elements that are common to all of the sets.)        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ 取交集,修改原来set """
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ 如果没有交集,返回true  """
        """ Return True if two sets have a null intersection. """
        pass

    def issubset(self, *args, **kwargs): # real signature unknown
        """ 是否是子集 """
        """ Report whether another set contains this set. """
        pass

    def issuperset(self, *args, **kwargs): # real signature unknown
        """ 是否是父集 """
        """ Report whether this set contains another set. """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.        """
        pass

    def remove(self, *args, **kwargs): # real signature unknown
        """ 移除 """
        """
        Remove an element from a set; it must be a member.
        
        If the element is not a member, raise a KeyError.        """
        pass

    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """ 差集,创建新对象"""
        """
        Return the symmetric difference of two sets as a new set.
        
        (i.e. all elements that are in exactly one of the sets.)        """
        pass

    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ 差集,改变原来 """
        """ Update a set with the symmetric difference of itself and another. """
        pass

    def union(self, *args, **kwargs): # real signature unknown
        """ 并集 """
        """
        Return the union of sets as a new set.
        
        (i.e. all elements that are in either set.)        """
        pass

    def update(self, *args, **kwargs): # real signature unknown
        """ 更新 """
        """ Update a set with the union of itself and others. """
        pass

    def __and__(self, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x. """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iand__(self, y): # real signature unknown; restored from __doc__
        """ x.__iand__(y) <==> x&=y """
        pass

    def __init__(self, seq=()): # known special case of set.__init__
        """
        set() -> new empty set object
        set(iterable) -> new set object
        
        Build an unordered collection of unique elements.
        # (copied from class doc)        """
        pass

    def __ior__(self, y): # real signature unknown; restored from __doc__
        """ x.__ior__(y) <==> x|=y """
        pass

    def __isub__(self, y): # real signature unknown; restored from __doc__
        """ x.__isub__(y) <==> x-=y """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __ixor__(self, y): # real signature unknown; restored from __doc__
        """ x.__ixor__(y) <==> x^=y """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __or__(self, y): # real signature unknown; restored from __doc__
        """ x.__or__(y) <==> x|y """
        pass

    def __rand__(self, y): # real signature unknown; restored from __doc__
        """ x.__rand__(y) <==> y&x """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __ror__(self, y): # real signature unknown; restored from __doc__
        """ x.__ror__(y) <==> y|x """
        pass

    def __rsub__(self, y): # real signature unknown; restored from __doc__
        """ x.__rsub__(y) <==> y-x """
        pass

    def __rxor__(self, y): # real signature unknown; restored from __doc__
        """ x.__rxor__(y) <==> y^x """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ S.__sizeof__() -> size of S in memory, in bytes """
        pass

    def __sub__(self, y): # real signature unknown; restored from __doc__
        """ x.__sub__(y) <==> x-y """
        pass

    def __xor__(self, y): # real signature unknown; restored from __doc__
        """ x.__xor__(y) <==> x^y """
        pass

    __hash__ = None

Python基础(一)_二进制_12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
练习:寻找差异
# 数据库中原有
old_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
    "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}
 
# cmdb 新汇报的数据
new_dict = {
    "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
    "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
    "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}
 
需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新

Python基础(一)_十进制_14demo 

九、collection系列

1、计数器(counter)

Counter是对字典类型的补充,用于追踪值的出现次数。

ps:具备字典的所有功能 + 自己的功能

1
2
3
c = Counter('abcdeabcdabcaba')
print c
输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Python基础(一)_十进制_15Counter

2、有序字典(orderedDict )

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

Python基础(一)_八进制_16OrderedDict

3、默认字典(defaultdict) 

学前需求:

1
2
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}

Python基础(一)_result_17原生字典解决方法

Python基础(一)_十六进制_18defaultdict字典解决方法

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

Python基础(一)_十六进制_19defaultdict

4、可命名元组(namedtuple) 

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。

1
2
3
import collections
 
Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])

Python基础(一)_十进制_20Mytuple

5、双向队列(deque)

一个线程安全的双向队列

Python基础(一)_十进制_21deque

注:既然有双向队列,也有单项队列(先进先出 FIFO )

Python基础(一)_十进制_22Queue.Queue

迭代器和生成器

一、迭代器

对于Python 列表的 for 循环,他的内部原理:查看下一个元素是否存在,如果存在,则取出,如果不存在,则报异常 StopIteration。(python内部对异常已处理)

Python基础(一)_二进制_23listiterator

二、生成器

range不是生成器 和 xrange 是生成器

readlines不是生成器 和 xreadlines 是生成器

1
2
3
4
>>> print range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print xrange(10)
xrange(10)

生成器内部基于yield创建,即:对于生成器只有使用时才创建,从而不避免内存浪费

1
2
3
4
5
6
7
8
9
10
11
练习:<br>有如下列表:
    [13, 22, 6, 99, 11]
 
请按照一下规则计算:
13 22 比较,将大的值放在右侧,即:[13, 22, 6, 99, 11]
22 6 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]
22 99 比较,将大的值放在右侧,即:[13, 6, 22, 99, 11]
99 42 比较,将大的值放在右侧,即:[13, 6, 22, 11, 99,]
 
13 6 比较,将大的值放在右侧,即:[6, 13, 22, 11, 99,]
...

Python基础(一)_十进制_24Demo

深浅拷贝

为什么要拷贝?

1
当进行修改时,想要保留原来的数据和修改后的数据

数字字符串 和 集合 在修改时的差异? (深浅拷贝不同的终极原因)

1
2
3
在修改数据时:
    数字字符串:在内存中新建一份数据
         集合:修改内存中的同一份数据

对于集合,如何保留其修改前和修改后的数据?

1
在内存中拷贝一份

对于集合,如何拷贝其n层元素同时拷贝?

1
深拷贝

思考  开发一个简单的计算器程序
  *实现对加减乘除、括号优先级的解析,并实现正确运算