python基础

一、python三元运算

二、基本数据类型之集合

三、赋值和深浅拷贝

四、自定义函数的创建、调用和函数参数

一、python三元运算

  result = 值1 if 条件 else 值2  :如果条件成立则result等于值1 ,否则等于值2

二、set 集合

  1. set 是一个无序且不重复的元素集合,支持并集、交集、差集、对称差集等数学运算,set不记录元素位置,因此不支持索引,分片等操作。
  2. 声名方法:    

    SET_NAME = set()

    SET_NAME = {1,2,3,4.....}  (不能用此方法创建空集合,系统会认为是创建一个空字典。)方法:

  3.方法:

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
        """ Remove all elements of another set from this set. 
        从当前集合中删除和b中相同的元素
        """
        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
        """
        Return the intersection of two sets as a new set.
        返回两个集合的交集将其生成一个新的集合
        (i.e. all elements that are in both sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. 
        取交集并更新到A中
        """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. 
        如果没有交集则返回True,否则返回False
        """
        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. 
        对称交集,并更新到A中
        """
        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, *args, **kwargs): # real signature unknown
        """ Return self&value. """
        pass

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

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __iand__(self, *args, **kwargs): # real signature unknown
        """ Return self&=value. """
        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, *args, **kwargs): # real signature unknown
        """ Return self|=value. """
        pass

    def __isub__(self, *args, **kwargs): # real signature unknown
        """ Return self-=value. """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __ixor__(self, *args, **kwargs): # real signature unknown
        """ Return self^=value. """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __rand__(self, *args, **kwargs): # real signature unknown
        """ Return value&self. """
        pass

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

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __rsub__(self, *args, **kwargs): # real signature unknown
        """ Return value-self. """
        pass

    def __rxor__(self, *args, **kwargs): # real signature unknown
        """ Return value^self. """
        pass

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

    def __sub__(self, *args, **kwargs): # real signature unknown
        """ Return self-value. """
        pass

    def __xor__(self, *args, **kwargs): # real signature unknown
        """ Return self^value. """
        pass

    __hash__ = None
View Code

三、赋值和深浅拷贝

赋值:a = 3 

   b = a 

  a,b指向同一片内存地址,可以使用id()来查看,赋值操作不会开辟新的内存空间,它只是复制了新对象的引用。在这只是增加了b这个变量名的内存。

如果想修改一个对象并且让原始对象不受影响,就需要进行复制(拷贝)操作。

数字的字符串还能被拷贝

如果元组内只包含数字或字符串则不能深拷贝

1.浅拷贝(shallow copy):

  创建方式:

    import copy

    copy.copy()

浅拷贝在内存中只额创建第一层数据。

import copy

n1 = {'k1':'wu','k2':123;'k3':['alex',456]}

n3 = copy.copy(n1)

 

2.深拷贝:

创建方式:

 import copy

   copy.deepcopy()

深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对数字和字符串的优化。)

import copy

n1 = {'k1':'wu','k2':123,'k3':['alex',456]}

n4 = copy.deepcopy(n1)

 

 

 

 四、自定义函数的创建、调用和函数参数

 函数是将一些代码组织到一起可以实现特定功能的代码块,将重复率较高的代码封装到函数中,需要时调用函数就可以实现功能。

1.自定义函数的创建

def 函数名(形参):
    函数体
    ....
    返回值
  • def:创建函数的关键字
  • 函数名:函数的名称,以后可根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑运算
  • 形参:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据,如果不指定默认返回None

 2.调用和传参

   用函数名调用函数

函数参数:

 

参数

 

以下是调用函数时可使用的正式参数类型:

 

  • 必备参数
  • 关键字参数
  • 默认参数
  • 不定长参数

 

必备参数

 

必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。

 

调用printme()函数,你必须传入一个参数,不然会出现语法错误:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme();

 

以上实例输出结果:

 

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();
TypeError: printme() takes exactly 1 argument (0 given)

 

关键字参数

 

关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。

 

使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。

 

以下实例在函数 printme() 调用时使用参数名:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme( str = "My string");

 

以上实例输出结果:

 

My string

 

下例能将关键字参数顺序不重要展示得更清楚:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );

 

以上实例输出结果:

 

Name:  miki
Age  50

 

缺省参数

 

调用函数时,缺省参数的值如果没有传入,则被认为是默认值。下例会打印默认的age,如果age没有被传入:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
#可写函数说明
def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;
 
#调用printinfo函数
printinfo( age=50, name="miki" );
printinfo( name="miki" );

 

以上实例输出结果:

 

Name:  miki
Age  50
Name:  miki
Age  35

 

不定长参数

 

你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。基本语法如下:

 

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

 

加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可。如下实例:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print "输出: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );

 

以上实例输出结果:

 

输出:
10
输出:
70
60
50

 


 

匿名函数

 

python 使用 lambda 来创建匿名函数。

 

  • lambda只是一个表达式,函数体比def简单很多。
  • lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
  • lambda函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。
  • 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。

 

 

变量作用域

一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪里赋值的。

变量的作用域决定了在哪一部分程序你可以访问哪个特定的变量名称。两种最基本的变量作用域如下:

 

  • 全局变量
  • 局部变量

全局变量和局部变量

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print "函数内是局部变量 : ", total
   return total;
 
#调用sum函数
sum( 10, 20 );
print "函数外是全局变量 : ", total 

以上实例输出结果:

函数内是局部变量 :  30
函数外是全局变量 :  0

 

posted @ 2016-05-09 07:10  Echo/  阅读(970)  评论(0编辑  收藏  举报