python基础(三)

集合

集合是一个无序的,不重复的数据组合。

主要作用是:1. 去重,把一个列表变成集合,就自动去重了。 2. 关系测试,测试两组数据之间的交集,差集,并集等关系。

__author__ = 'meng'

list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
print (list_1,type(list_1))

list_2 = set([2,6,0,66,22,8,4])
print (list_1,list_2)

#交集
print (list_1.intersection(list_2))
#并集
print (list_1.union(list_2))
#差集 in list_1 not in list_2
print (list_1.difference(list_2))
#差集 in list_2 not list_1
print (list_2.difference(list_1))

list_3 = set([1,3,7])
#子集
print (list_3.issubset(list_1)) #list_3 是 list_1 的子集
#父集
print (list_1.issuperset(list_3)) #list_1 是 list_3 的父集
#对称差集  把两个集合里面重复的去掉。
print (list_1.symmetric_difference(list_2))

list_4 = set([5,6,8])
#判断是否是相交集,如果不存在相交集,返回 True
print (list_3.isdisjoint(list_4))

  

对应下面输出结果

常用操作:

list_1 = set([1,4,5,7,3,6,7,9])
list_2 = set([2,6,0,66,22,8,4])

#交集
print (list_1 & list_2)
#并集(union)
print (list_1 | list_2)
#差集(difference)
print (list_1 - list_2) # in list_1 not in list_2
#对称差集
print (list_1 ^ list_2)  #把2个集合里面重复的去掉
print ("-------基本操作-------")
list_1.add(999)           #添加一项
print (list_1)
list_1.update([444,7777,555]) #在集合list_1中添加多项
print (list_1)
list_1.remove(6) #删除一项
print (list_1)
print (len(list_1)) #判断set的长度

print (9 in list_1) #测试 x 是否是集合 list_1 的成员
print (9 not in list_1) # 测试 x 是否不是 集合 list_1的成员

print (list_1.copy()) #返回集合 list_1的一个浅copy
list_1.remove(555) #指定删除一个
print (list_1)
print (list_1.discard(888)) #discard不存在不会报错,执行完返回 None
print (list_1)
list_1.pop() #任意删除一个,指定删除用 remove
print (list_1)
list_1.pop()
print (list_1)

  对应如下输出结果:

 二、文件操作

文件操作流程:

1.打开文件。

2.操作文件。

3.关闭文件。

文件读写:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

f=open('f.txt','w',encoding='utf-8') # r只读,w可写,a追加
for i in range(8,15):
    f.write(str(i)+'
')

f.close() #关闭文件

f.txt文件内容输出结果如下:
8
9
10
11
12
13
14

# r    只读文件。

# rb 二进制读文件。

# r+ 可读可写,不会创建不存在的文件 从头部开始写,会覆盖之前此位置的内容 。

# rb+ 二进制格式读写文件。文件指针将会放在文件的开头。

# w    只写文件,如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

# wb 二进制写文件。

# w+ 读写文件。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

# wb+ 二进制读写文件。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

# a    只追写文件。从文件底部添加内容 不存在则创建 。

# ab 二进制追写文件。 从文件顶部读取内容 从文件底部添加内容 不存在则创建。

# a+ 追读写文件。从文件顶部读取内容 从文件底部添加内容 不存在则创建。

# ab+ 追读写二进制。从文件顶部读取内容 从文件底部添加内容 不存在则创建。

 

with语句:

为了避免打开文件后忘了关闭,当with代码执行完之后,内部会自动关闭并释放文件资源。

__author__ = 'meng'
#自动关闭文件
with open("here","r",encoding="utf-8") as f :
    for line in f:
        print (f.readline())
'''
#同时打开多个文件
with open("here","r",encoding="utf-8") as f ,
     open("here.bak","w",encoding="utf-8") as f2:
'''

  

 文件操作之增删改查:

here:

To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
我只想和你在此相伴,不想去任何其他地方
Than here with you
不想去任何其他地方
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~
Ain't felt this good since I remember
记忆中从未感觉如此美好
This night got started when you entered
你的到来让今夜变得闪亮
I hope we can get a little closer
希望我们能有更多了解
Maybe even get to know your name
或许只需要知道你的名字
I wanna hear the music so loud
我希望音乐更疯狂
Get some drinks inside me right now
此刻,我只想来点美酒
So baby let it go
所以,宝贝,不要犹豫
You had me at hello
你只需打个招呼我就会跟你走
Let's raise our glass and toast
让我们举杯畅饮
DJ play that once more
DJ让音乐再次唱响
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
我只想和你在此相伴
Than here with you
不想去任何其他地方
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~
Gonna see the sun
还未意识到
Before we know it
太阳就要升起
If you got some money
还有金钱的话
Time to blow it
尽情挥洒掉吧
Girl, way you got me feeling so sick
女孩,你让我感觉如此疯狂
Dancing the night
与你彻夜共舞
Away with you, with you, with you yeah
让我十分满足,无比满足
Nobody here is sober
今夜让我们一起疯狂
Last call don't mean it's over yeah
最后的招待并不代表就要结束
So baby let it go
所以,宝贝,不要犹豫
You had me at hello
你只需打个招呼我就会跟你走
Let's raise our glass and toast
让我们举杯畅饮,尽情享受
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
不想去任何其他地方
Than here with you
我只想和你在此相伴
Than here with you
有你相伴就是天堂
Than here with you
和你在一起
Oh oh oh oh oh oh
哦哦哦哦哦~
Than here with you
有你相伴就是天堂
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~
I wanna hear the music so loud yeah
我想让音乐更大声些
I wanna hear the music so loud yeah
我想让音乐更疯狂些
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
不想去任何其他地方
Than here with you
我只想和你在此相伴
Than here with you
有你相伴就是天堂
Than here with you
和你在一起
Oh oh oh oh oh oh
哦哦哦哦哦~
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
哦哦哦哦哦~

  文件修改:

__author__ = 'meng'
#文件修改,被修改的文件写入到 新文件 here.bak 里面
f = open("here","r",encoding="utf-8")
f_new = open("here.bak","w",encoding="utf-8")

for line in f:
    if "哦哦哦哦哦~" in line:
        line = line.replace("哦哦哦哦哦~","啊啊啊啊啊!") #旧的字符串"哦哦哦哦哦~"被替换成 "啊啊啊啊啊!
    f_new.write(line)
f.close() 
f_new.close()

  here.bak内容

To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
我只想和你在此相伴,不想去任何其他地方
Than here with you
不想去任何其他地方
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!
Ain't felt this good since I remember
记忆中从未感觉如此美好
This night got started when you entered
你的到来让今夜变得闪亮
I hope we can get a little closer
希望我们能有更多了解
Maybe even get to know your name
或许只需要知道你的名字
I wanna hear the music so loud
我希望音乐更疯狂
Get some drinks inside me right now
此刻,我只想来点美酒
So baby let it go
所以,宝贝,不要犹豫
You had me at hello
你只需打个招呼我就会跟你走
Let's raise our glass and toast
让我们举杯畅饮
DJ play that once more
DJ让音乐再次唱响
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
我只想和你在此相伴
Than here with you
不想去任何其他地方
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!
Gonna see the sun
还未意识到
Before we know it
太阳就要升起
If you got some money
还有金钱的话
Time to blow it
尽情挥洒掉吧
Girl, way you got me feeling so sick
女孩,你让我感觉如此疯狂
Dancing the night
与你彻夜共舞
Away with you, with you, with you yeah
让我十分满足,无比满足
Nobody here is sober
今夜让我们一起疯狂
Last call don't mean it's over yeah
最后的招待并不代表就要结束
So baby let it go
所以,宝贝,不要犹豫
You had me at hello
你只需打个招呼我就会跟你走
Let's raise our glass and toast
让我们举杯畅饮,尽情享受
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
不想去任何其他地方
Than here with you
我只想和你在此相伴
Than here with you
有你相伴就是天堂
Than here with you
和你在一起
Oh oh oh oh oh oh
啊啊啊啊啊!
Than here with you
有你相伴就是天堂
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!
I wanna hear the music so loud yeah
我想让音乐更大声些
I wanna hear the music so loud yeah
我想让音乐更疯狂些
To all my friends
对我所有好友来讲
The night is young
夜未央
The music's loud
乐未殇
They playing our song
他们在我们喜爱的歌声里欢畅
Nowhere else that I belong
不想去任何其他地方
Than here with you
我只想和你在此相伴
Than here with you
有你相伴就是天堂
Than here with you
和你在一起
Oh oh oh oh oh oh
啊啊啊啊啊!
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!
Than here with you
有你相伴就是天堂
Oh oh oh oh oh oh
啊啊啊啊啊!

 第二种比较方便灵活的修改方法: 

__author__ = 'meng'
import sys
f = open("here","r",encoding="utf-8")
f_new = open("here.bak","w",encoding="utf-8")
find_str = sys.argv[1]  #传递旧参数
replace_str = sys.argv[2] #新的修改后的参数
for line in f:
    if find_str in line:
        line = line.replace(find_str,replace_str) #旧的字符串被替换成 新的。
    f_new.write(line)
f.close()
f_new.close()

  修改结果如下:

字符编码与转码

 函数

1.面向对象:-----类-----class

2.面向过程:-----过程---def

3.函数式编程:----函数---def

函数三大优点:

1.代码重用。2.保持一致性。3.可扩展性。

__author__ = 'meng'
#函数的三大优点
# 1.代码重用 2.保持一致性 3.可扩展性
import time

def logger():
    time_format = "%Y-%m-%d %X"
    time_current = time.strftime(time_format)
    with open ("a.txt","a+") as f:
        f.write('%s e actionnd
' %time_current)

def test1():
    print ("in the test1")
    logger()

def test2():
    print ("in the test2")
    logger()

def test3():
    print ("in the test3")
    logger()

test1()
test2()
test3()

输出结果如下,实现代码重用

函数返回值

__author__ = 'meng'
def test1():
    print ("in the test1")

def test2():
    print ("in the test2")
    return 0

def test3():
    print ("in the test3")
    return 3,"AK-47",["SB",23,"abc"],{"Tom":"23"}
    #return test2  #返回test2的内存地址
x = test1()
y = test2()
z = test3()

print (x)
print (y)
print (z)

#函数返回值
#返回值数=0,返回 None  (不写return值,返回 None)
#返回值数=1,返回object (返回具体数字)
#返回值数>1,返回typle,  (以元组的形式返回)

函数参数及调用

__author__ = 'meng'
#x,y是形参
def test(x,y):
    print (x)
    print (y)

test(2,3) #与形参一一对应
test(y=4,x=6)#与形参顺序无关

  

__author__ = 'meng'

#第一种类型 参数组
def test(*args):
    print (args)

test(1,2,3,4,5,5)
test(*[1,2,3,5,5]) #args=tuple([1,2,3,5,5])

  

#**kwargs 把N个关键字参数转换成字典的方式
def test2(**kwargs):
    print (kwargs)

test2(name="Meng",age=23,job="it")
test2(**{"name":"Meng","age":"23","job":"it"})

  

def test4(name,age=23,*args,**kwargs):
    print (name)
    print (age)
    print (args)
    print (kwargs)

test4("meng",sex="man",job="it")
test4("Li",**{"sex":"man","job":"it"})

  

作用域局部变量与全局变量

__author__ = 'meng'
#局部变量只在函数里生效,

school = "oldboy edu." #全局变量
def change_name(name):
    global school  #把局部变量改成全局变量
    school = "Mage linux"
    print ("before change",name,school)
    name = "Meng" #这个函数就是这个变量的作用域
    print ("after change",name)


name = "Li"
change_name(name)
print (name)
print ("school:",school)

  

#列表,字典,集合,类 ,可以在局部里面改全局,字符串和整数不能在局部里面改全局

names = ["Tom","AK-47","23"]

def change_name():
    names[0]="M4A1-S"
    print ("names:",names)

change_name()
print (names)

  

高阶函数

以python内置求绝对值函数abs()为例。

>>> abs(-10)
10
>>> abs  # abs(-10)是函数调用,而abs是函数本身。
<built-in function abs>
>>> x = abs(-10) #要想函数调用结果,我们可以把结果赋值给变量
>>> x
10
>>> f = abs #变量f现在已经指向了abs函数本身。直接调用abs()函数和调用变量f()完全相同
>>> f(-10)
10

 总结:变量可以指向函数。

把函数作为参数传入,这样的函数称为高阶函数。

定义一个简单的高阶函数如下:

def add(x, y, f):
    return f(x) + f(y)


x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11

#当我们调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs,根据函数定义,我们可以推导计算过程为:11
>>> add(-5, 6, abs)
11

  

原文地址:https://www.cnblogs.com/menglingqian/p/6270077.html