文章目录

  • 1.集合
  • 2.文件操作
  • 3.函数
  • 4.局部变量

1.集合

  集合是一个无序的,不重复的数据组合,它的主要作用如下:

  1)去重,把一个列表变成集合,就自动去重了
  2)关系测试,测试两组数据之前的交集、差集、并集等关系
常用操作:

list_1 = [1,3,5,6,7,8,12]
list_2 = [0,3,4,7,5,1,43]list_1 = set(list_1)
list_2 = set(list_2)
print(list_1,type(list_1))  #{1, 3, 5, 6, 7, 8, 12} <class 'set'>

取交集:

print(list_1.intersection(list_2))  #{1, 3, 5, 7}
#or
print(list_1 & list_2)

取并集:

print(list_1.union(list_2)) #{0, 1, 3, 4, 5, 6, 7, 8, 43, 12}
#or
print(list_1 | list_2)

取差集:

#取 list1 中有的而 list2 中没的
print(list_1.difference(list_2))    #{8, 12, 6}
#or
print(list_1 - list_2)

判断是否是子集、父集:

list_3 = set([1,3,7])
print(list_3.issubset(list_1))  #True
print(list_1.issuperset(list_3))    #True

对称差集-------并集的基础上去除交集:

print(list_1.symmetric_difference(list_2))  #{0, 4, 6, 8, 43, 12}
#or
print(list_1 ^ list_2)

判断是否有交集,若无,返回True:

list_4 = set([2,4,6])
print(list_3.isdisjoint(list_4))    #True

添加与删除:

list1 = set([1,2,3,5,8,10])list1.add(15) #添加一项
list1.update([20,30,40])  #添加多项
print(list1)list1.remove(1) #删除
list1.pop() #随机删

2.文件操作

对文件操作流程:
  1)打开文件,得到文件句柄并赋值给一个变量
  2)通过句柄对文件进行操作
  3)关闭文件

打开文件的模式有:r,只读模式(默认)。
w,只写模式。【不可读;不存在则创建;存在则删除内容;】
a,追加模式。【可读;   不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件r+,可读写文件。【可读;可写;可追加】
w+,写读
a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)rb
wb
ab

现有文件如下,文件取名为 yesterday:

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂

基本操作:
读:

#读整个文件
data = open('yesterday',encoding='utf-8').read()
print(data)f = open('yesterday','r',encoding='utf-8') #文件句柄
data = f.read()
data2 = f.read()
print(data)
print('-----data2-----',data2)  #第二次读时会从第一次读的位置接下去读#r 读
f = open('yesterday','r',encoding='utf-8')
#读一行
f.readline()#读五行
for i in range(5):print(f.readline())# 不适合读大文件
for index,line in enumerate(f.readlines()):if index == 9:  #实现第九行不打印print('-------------------')continueprint(line.strip()) #去除每一行后的空格#每次只读一行,适合大文件
for line in f:print(line)

写、追加:

#w 写
f = open('yesterday2','w',encoding='utf-8')
f.write('我爱北京天安门,\n')
f.write('天安门上太阳升')#a = append 追加
f = open('yesterday2','a',encoding='utf-8')
f.write('\nwhen i was yong i listen to the radio\n')f.close()

获取当前索引位置、获取文件编码:

print(f.tell()) #0
print(f.readline())
print(f.tell()) #72
f.seek(0)   #将文件中的索引位置移到 0
print(f.tell()) #0#获取文件编码
print(f.encoding)

文件截断:

f1 = open('yesterday2','a',encoding='utf-8')#从头开始截断10个字符(只保留10个,其他的删除)
f1.truncate(10)

读写:

#r+ 为读写,未开始读时,写为从第一行开始覆盖写,读过之后,写为从最后一行追加写
f1 = open('yesterday2','r+',encoding='utf-8')
#print(f1.readline())
print(f1.readline())
f1.write('---------------------')
f1.close()

写读:

#w+ 为写读,但会先创建一个文件再写,写为覆盖,而不是将原先内容后移后再写
f1 = open('yesterday2','r+',encoding='utf-8')
print(f1.tell())
f1.write('-------------------1\n')
print(f1.tell())
f1.write('-------------------1\n')
print(f1.tell())f1.seek(10)
print(f1.tell())
f1.write("yleaveaaaaaaaaaaaaaaaaaa")f1.close()

二进制读写:

#rb+ 为以二进制编码读写
f = open('yesterday2','rb+')print(f.readline())
f.write('hello binary'.encode())

with 语句:
为了避免打开文件后忘记关闭,可以通过管理上下文,即:

# with 可自动关闭文件,末尾不用加 close
with open('yesterday','r',encoding='utf-8') as f:print(f.readline())for line in f:print(line)#同时打开多个文件
with open('yesterday','r',encoding='utf-8') as f1,\open('yesterday2','r',encoding='utf-8') as f2:for line in f:print(line)

文件修改:
将原文件中的内容保存到新文件中:

f = open('yesterday','r',encoding='utf-8')
f_new = open('yesterday.bak','w',encoding='utf-8')for line in f:if '肆意的快乐等我享受' in line:line = line.replace('肆意的快乐等我享受','肆意的快乐等yleave享受')f_new.write(line)
f.close()
f_new.close()

实现简单的shell sed替换功能:

import sys
find_str = sys.argv[0]
replace_str = sys.argv[1]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()

模拟进度条功能(利用flush函数):

import sys,timefor i in range(30):sys.stdout.write("#")sys.stdout.flush()time.sleep(0.1)

3.函数

  定义: 函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可

特性:
  1)减少重复代码
  2)使程序变的可扩展
  3)使程序变得易维护

语法定义:

def sayhi():#函数名print("Hello, I'm nobody!")sayhi() #调用函数

简例:

def func1(x):x += 1print('func1')print(x)    # 1return xdef func2():print('func2')x = 0
func1(x)
func2()
print(x)    # 0

使用函数可简化代码:

import timedef logger():time_format = '%Y-%m-%d %X'time_current = time.strftime(time_format)with open('a.txt','a+') as f:f.write('%s end action\n' %time_current)def text1():print('text1')logger()def text2():print('text2')logger()def text3():print('text3')logger()text1()
text2()
text3()'''a.txt
2019-07-05 14:20:56 end action
2019-07-05 14:20:56 end action
2019-07-05 14:20:56 end action
'''

三种函数:

def test1():print("in test1")def test2():print('in test2')return 0def test3():print('in test3')return 1,'hello',['alex','yleave'],{'name':'yleave'}x = test1()
y = test2()
z = test3()print(x)    #None
print(y)    #0
print(z)    #(1, 'hello', ['alex', 'yleave'], {'name': 'yleave'})

关键参数:
  正常情况下,给函数传参数要按顺序,不想按顺序就可以用关键参数,只需指定参数名即可,但记住一个要求就是,关键参数必须放在位置参数之后。

def text(x,y,z):print(x)print(y)print(z)x = 1
y = 2
text(1,2,3)
text(x,z = 3,y = 3)

默认参数:

def test1(x,y = 2):print(x)print(y)test1(1,3) # 1 3
test1(1)    # 1 2

非固定参数:
若你的函数在定义时不确定用户想传入多少个参数,就可以使用非固定参数

def test(*args):print(args)test(1,2,3,4,5)
test(*[1,2,3,4,4])  #args = tuple([1,2,3,4,4])
#输出:(1, 2, 3, 4, 4)def test1(x,*args):print(x)print(args)test1(1,2,3,4,5)def test2(*args,x):print(x)print(args)test2(1,2,3,4,x = 1)

字典传递:

#**kwards: 把 N 个关键字参数转换成字典的方式
def test3(**kwargs):print(kwargs)test3(name = 'yleave',age = 22,sex = 'F')   #{'name': 'yleave', 'age': 22, 'sex': 'F'}
test3(**{'name':'alex','age':22})   #{'name': 'alex', 'age': 22}def test4(**kwargs):print(kwargs)print(kwargs['name'])print(kwargs['age'])print(kwargs['sex'])test4(name = 'yleave',age = 22,sex = 'F')
'''
yleave
22
F
'''def test5(name,age = 22,**kwargs):print(name)print(age)print(kwargs)test5('yleave',sex = 'f',job = 'studnet')

4.局部变量

  在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
  全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
  当全局变量与局部变量同名时:
  在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。

name1 = 'alex'def change_name(name):global name1name1 = 'yle'name = 'yleave'change_name(name = name1)
print(name1)    #yle#除了字符串和数字在函数中不能改变值外,列表、字典、集合、类等数据结构都能在函数中修改
names = ['alex','yleave']
def test():names[0] = 'ALEX'print('inside func',names)test()
print(names)    #['ALEX', 'yleave']

高阶函数:

def add(a,b,f):return f(a) + f(b)print(add(3,-6,abs))   #传入的参数是函数  result:9

day3 集合、文件操作、函数、局部变量相关推荐

  1. 跟着ALEX 学python day3集合 文件操作 函数和函数式编程

    声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/  一. 集合 集合是一个无序的,不重复的数据组合,主要作用如下 1.去重 把一个列表变成集合 ,就自动去重 ...

  2. 文件操作函数在VFS层的实现

    文件操作函数在VFS层的实现 参考"Understanding Linux kernel"中的"12.6 Implementations of VFS System Ca ...

  3. C/C++,C++文件操作函数

    目录 一.标准文件函数 [1]文件的打开和关闭 [2]文件操作的函数 [3]文件的随机读写 [4]读写指针位置操作 二.非标准文件函数 [1] 文件的打开与关闭 [2]读写函数 [3]随机定位函数 三 ...

  4. Python集合文件操作Day03

    集合 主要作用: 去重 关系测试, 交集\差集\并集\反向(对称)差集 集合也是一种数据类型,一个类似列表东西,它的特点是无序的,不重复的,也就是说集合中是没有重复的数据 #集合定义 list_1 = ...

  5. 使用文件操作函数实现:文件的复制功能。

    2019独角兽企业重金招聘Python工程师标准>>> //使用文件操作函数实现:文件的复制功能. #include <stdio.h> #include <std ...

  6. php文件有哪几种,PHP常用的文件操作函数有哪些

    PHP常用的文件操作函数有哪些 本文主要总结的PHP文件操作函数.当然,这只是部分,还有很多,我没有列出来.欢饮阅读参考! 一 .解析路径: 1 获得文件名: basename(); 给出一个包含有指 ...

  7. 【C 语言】文件操作 ( C 语言中的文件操作函数 | 磁盘与内存缓冲区 | 缓冲区工作机制 )

    文章目录 一.C 语言中的文件操作函数 二.磁盘与内存缓冲区 三.缓冲区工作机制 一.C 语言中的文件操作函数 读取 文本文件 可以使用 getc , fgets , fscanf 函数 , 向 文本 ...

  8. python中对文件、文件夹(文件操作函数)的操作

    python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() 返回指定目录下的所有文件和目 ...

  9. C语言文件操作函数大全(看到总结的真的很好,就转载贡献给大家了)

    C语言文件操作函数大全 clearerr(清除文件流的错误旗标) 相关函数 feof 表头文件 #include<stdio.h> 定义函数 void clearerr(FILE * st ...

  10. Python--set集合讲解; 什么是集合?创建一个集合;集合的操作函数;

    什么是集合? 创建一个集合 第一种方式: set={"1","2"} 第二种方式 list = ['1','2'] set1 = set(list) 集合的操作 ...

最新文章

  1. odoo13中的模型类中的方法函数ORM方法以及模型方法的装饰器
  2. 华为升级harmonyos的机型名单,华为鸿蒙 OS 2.0 系统适配名单已出,四月推送,天玑机型暂时无缘...
  3. osi模型:七层模型介绍_联网| OSI模型能力问题和解答 套装1
  4. 推荐:CLR 完全介绍-一篇讲解CLR内存回收机制以及常见的调试技巧的文章
  5. 小鹏吃相难看,消费者难做“鹏”友
  6. mysql_udf_http(根据mysql表自动触发发送http请求)
  7. WebDAV被启用(转)
  8. 引言:扇贝 2017 服务端技术回顾
  9. python 智能造句_用python中的markov链造句
  10. 影响你成功最重要的两种人
  11. ArduinoUNO实战-第十四章-LM35温度传感器和DS18B20温度传感器
  12. 大专计算机课教案,计算机课教案
  13. 机器学习之PCA算法的人脸图像识别-平均脸的计算(详细操作步骤)
  14. H-Index H指数
  15. 小鸟云服务器怎么进行启动和关机?
  16. 堆Heap块Chunk
  17. python面试项目案例
  18. POI Excel插入线条(直线、斜线)
  19. 微信公众平台流量主单日广告收入最高达5万元 羡煞偶们
  20. ckplayer html5 添加广告,CKplayer纯净播放器设置示例(可不显示广告)

热门文章

  1. Java-----applet小程序简介
  2. C#拾遗系列(4):索引器
  3. JDK8:Lambda表达式操作List集合
  4. Mysql的日志那些事
  5. ThreadLocal为什么要使用弱引用和内存泄露问题
  6. 某华为程序员爆料:主动离职,公司竟也给n+1,到手15万,华为真良心!
  7. Leader每天996,绩效被打C!CTO说,团队带不好,原因只有一个
  8. 华为员工实力炫富,工作六年一套房一辆豪车,存款六十万
  9. 石墨文档技术总监:敏捷思想在产品周期的延伸
  10. 有什么好用的SaaS软件推荐?