Python 基础之函数、深浅copy,set及练习

三元运算符通常在Python里被称为条件表达式,这些表达式基于真(true)/假(not)的条件判断,在Python 2.4以上才有了三元操作。

 语法格式:

X if C else Y

有了三元表达式,你只需一行就能完成条件判断和赋值操作:

 x, y = 3, 4
  if x<y :
    smaller= x
  else 
    smaller =y

现在 只需一句:

smaller = x  if x<y  else y  

基本数据类型补充之 set

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

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. A中存在,B中不存在
         
        (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

创建set:

s = set([1,2,3])
s = {1,2,3}

set函数:

s.add(x)		 #添加元素x到集合s
s.clear()		 #删除所有元素集
s.copy()		 #新设置的浅拷贝
s.difference(t)	 #差分操作: s 中的元素,而不是t 中的元素,通俗讲s中有的,t中没有的-->s - t	  
s.difference_update(t)	  #返回删除元素后集合s t-->s -= t
s.discard(t)		#如果t是集合s 中的元素,从集合s 中删除t
s.intersection(t)	#返回交集到新集合-->s & t	
s.intersection_update(t)	#取交集并更更新到s中-->s &= t	
s.isdisjoint(t)		#如果没有交集,返回True,否则返回False
s.issubset(t)	#s 中所有的元素都是t 的成员,子集 -->s <= t	
s.isupperset(t)# t 中所有的元素都是s 的成员,父集 -->	s >= t	
s.pop() 		#删除集合s 中的任意一个对象,并返回它
s.remove(x)		#从集合s 中删除对象x;如果x 不是集合s 中的元素(obj not in s),将引发KeyError 错误
s.symmetric_difference(t)	#对称差分操作:s 或t 中的元素,但不是s 和t 共有的元素-->s ^ t
symmetric_difference_update	#s 中的成员更新为那些包含在s 或t中,但不是s和t 共有的元素-->s ^= t	
s.union(t)	#合并操作:s 或t 中的元素--> s | t	
s.update(t) #用t 中的元素修改s, 即s 现在包含s 或t 的成员--> s |= t              

深浅copy

一、数字和字符串

1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
2. copy.deepcopy 深拷贝 拷贝对象及其子对象

ps:str,int 深浅copy内存地址都是一样的

import copy
# ######### 数字、字符串 #########
n1 = 123
# n1 = "i am alex age 10"
print(id(n1))
# ## 赋值 ##
n2 = n1
print(id(n2))
# ## 浅拷贝 ##
n2 = copy.copy(n1)
print(id(n2))
  
# ## 深拷贝 ##
n3 = copy.deepcopy(n1)
print(id(n3))

如下图:

 

对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

二、其他基本数据类型

1、赋值

赋值,只是创建一个变量,该变量指向原来内存地址,如:

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

 

2、浅拷贝

import copy
  
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  
n3 = copy.copy(n1)

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

如下图:

 

def fib3(a):
    if a ==0 or a ==1:
        return  a
    else:
        return (fib3(a-1)+fib3(a-2))
ret = fib3(10)
print(ret)

  

3、深拷贝

import copy
  
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
  
n4 = copy.deepcopy(n1)

 函数:

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。

函数定义规则:

  • 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

 参数:

  • 必备参数 :必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
  • 关键字参数 :关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。
  • 默认参数 :调用函数时,缺省参数的值如果没有传入,则被认为是默认值。 放在参数的尾部
  • 不定长参数:*args ,**kwargs

局部变量和全局变量

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

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

  • 全局变量
  • 局部变量

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中,如果想修改变全部变量就需要globals

#!/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

练习题

# 数据库中原有
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':'c1', 'cpu_count': 2, 'mem_capicity': 80 }
}

code:

# old_set = set(old_dict.keys())
# new_set = set(new_dict.keys())
#需要删除
# old_dict_a = old_set.difference(new_dict) #删除old_dict ,new_dict中没有的 ,
# old_set.remove(*old_dict_a)
# print(old_set)
#需要新建:?
# ret = new_set.difference(old_set)
# old_set.add(*ret)
# print(old_set)

#需要更新:?
#old_set.intersection_update(new_set)#new_dit中的值,old_set中 -->取交集更新到a 。

  

1、简述普通参数、指定参数、默认参数、动态参数的区别

普通参数 :普通参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
指定参数 :指定参数和函数调用关系紧密,函数调用使用指定参数来确定传入的参数值。
默认参数 :调用函数时,缺省参数的值如果没有传入,则被认为是默认值。 放在参数的尾部
动态参数:*args ,**kwargs 

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

def check_type(object):
    int_all = 0
    str_all = 0
    space_all = 0
    other_all = 0
    for i in object:
        if i.isdigit():
            int_all+=1
        elif i.isalpha():
            str_all+=1
        elif i.isspace():
            space_all+=1
        else:
            other_all+=1
    return ('数字:%s,字符串:%s,空格%s,其他:%s'%(int_all,str_all,space_all,other_all))
ret = check_type('asfa asddfa asf 23423 #@asf ')
print(ret)  

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

def is_object(object):
    if len(object) >=5:
        #print(object)
        return ('对象大于等于5')
    else:
        return ('对象小于5')
a = (11,22,33,4,5,)
ret = is_object(a)
print(ret)

4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

def check_object(object):
    for i in a:
        i = str(i)
        if ' '  in i:
            return ('空格元素:',i)
        else:
            return ('没有空格')
a = ('q wer','adf')
ret = check_object(a)
print(ret)

5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

def check_split(object):
    if len(object) >2:
        return (object[0:2])
    else:
        return object

ret = check_split(('11','113',12))
print(ret)

6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

def ol_num(object):
    rec = []
    for i in range(len(object)):
        if i %2 ==1:
            rec.append(object[i])
    return rec
ret = ol_num([11,222,3,4,5,6,78,89,9])
print(ret)

7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
 
PS:字典中的value只能是字符串或列表
def dic_lent(**object):
    new_dict = {}
    for k,v in object.items():
        if type(v) ==str:
            new_dict[k] =v[0:2]
            #print(new_dict)
        elif type(v) == list:
            new_dict[k] =v[0:2]
    return (new_dict)

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
ret = dic_lent(**dic)
print(ret)

精简版

def dic_lent(**object):
    new_dict = {}
    for k,v in object.items():
            new_dict[k] =v[0:2]
    return (new_dict)

dic = {"k1": [222,333,44,5,4], "k2": [11,22,33,44]}
ret = dic_lent(**dic)
print(ret)

8、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者。

def fib3(a):
    if 1 == a:
        return 0
    elif 2 ==a:
        return 1
    else:
        return (fib3(a-1)+fib3(a-2))
ret = fib3(10)
print(ret)
def func(arg1,arg2):
    if arg1 == 0:
        print arg1, arg2
    arg3 = arg1 + arg2
    print arg3
    func(arg2, arg3)
  
func(0,1)
View Code

  

  

  

原文地址:https://www.cnblogs.com/yyyg/p/5467925.html