Python函数

一、set集合

a、

创建

s = set() # 相当于无序且不重复的list

s = {11, 22, 33}# 也可以创建集合,当s = {}表示空字典

b、

转换

name_list = [11, 11, 22, 33]

s = set(name_list)

print(s)

效果:[11, 22, 33]

c、

add()# 添加功能

clear()# 清除功能,一朝做流氓,十年挂南墙

difference()# 我就是我,颜色不一样的烟火(我有你没有的集合),重新赋值才能看到效果

difference_update()#我有你没有的集合(秀优越,打死你)不用赋新值,也可以看到效果

pop()# 因为set集合是无序且不重复的,所以删除是随机的

discard()和remove()# 都是删除元素discard()没有会返回-1,remove()没有会报错

d、

intersection()

s1 = {11, 22, 33, 44}

s2 = {22, 33}

ret = s1.interction(s2)

print(ret)

s1.intersection_update(s2)

print(s1)

效果:

{22, 33}

{22, 33}

e、

isdisjoint()# 有交集返回False,没有交集返回True

s1 = {11, 22, 33, 44}

s2 = {22, 33}

s3 = {7, 8}

ret = s1.isdisjoint(s2)

ret = s1.isdisjoint(s3)

print(ret)

print(ret2)

效果:

False

True

f、

issubset()# 是否子序列

issuperset()# 是否父序列

s1 = {11, 22, 33, 44}

s2 = {22, 33, 11}

ret1 = s1.issuperset(s2)

ret2 = s2.issubset(s2)

print(ret1)

print(ret2)

效果:

True

True

g、

symmetric_difference() # 你有他没有的,他有你没有的,然后整个集合且得赋值才能看到效果

symmertric_difference_update #你有他没有的,他有你没有的,不用赋值也能看到效果

h、

union()# 并集

update()

s1 = {11, 22 ,33, 44}

s2 = {22, 33, 44, 55}

s1.update(s2)

print(s1)

s1.update([55, 66])

print(s1)

效果:

[11, 22, 33, 44, 55]

[11, 22, 33, 44, 55, 66]

i、

三元运算符

name = "jane" if True else "jen"

j、

函数

def fun():

    print("This is my life")

    return 18

 

ret = fun()

print(ret)

默认参数

def function(age, name="jane"):# 默认参数一定要放到形式参数后边

    temp = str(age) + ", " + name

    return temp

 

function(18)

对应关系

def function(age, name, country):

    temp = str(age) + " " + name + " " + country

    return temp

 

function(18, "jane", "China")# 形参与实参是一一对应的

function(name="jane", country = "China", age=18)# 也可以不一一对应

局部变量与全局变量

SEVEN = 7#全局变量,并且大写(约定俗成)

def function_one():

    sex = 6局部变量

    global SEVEN

    SEVEN = "7"

    print(sex)

 

def function_two():

    print(SEVEN)

 

function_one()

function_two()

return

def send():

    # return "I'm ok"

 

ret = send()

print(ret)# 当没有返回值时,返回None

动态参数

def function(*args):

    print(type(args))   

    print(args)

 

list_name = ['jane', 'logan']

function(list_name)

效果:

function(list_name)

<class 'tuple'>

(['jane', 'logan'],)

 

function(*list_name)

<class 'tuple'>

('jane', 'logan')

 

def function(**kwargs)

    print(kwargs, type(kwargs))

 

 

favorie_languages = {

    'jen': 'Python',

    'jane': 'Python',

}

function(name='jane', age=18)

function(**favoite_languages)# 不加**会报错

效果:

function(name='jane', age=18)

{'age': 18, 'name': 'jane'} <class 'dict'>

 

function(**favorite_languages)

 

{'jen': 'Python', 'jaymes': 'C++', 'jack': 'Rose'} <class 'dict'>

posted on 2017-09-08 17:22  我是自由的你别安排我  阅读(132)  评论(0)    收藏  举报

导航