python学习笔记3:集合,文件操作,函数

一.集合

1.

>>> s=set([1,2,3,4,5,6,6,6,])
>>> s
{1, 2, 3, 4, 5, 6}

集合可以理解为有键没有值的字典,键之间去重,无序。

2.集合操作:

>>> s1={1,2,3,4,5,6,7}
>>> s2={6,7,8,9,10,11}
>>> s1&s2
{6, 7}//交集
>>> s1|s2
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}//并集
>>> s1^s2
{1, 2, 3, 4, 5, 8, 9, 10, 11}//差集

3.添加和删除元素

>>> s=set([1,2,3,4,5,5,5,8])
>>> s
{1, 2, 3, 4, 5, 8}
>>> s.add('hello')
>>> s
{1, 2, 3, 4, 5, 'hello', 8}
>>> s.remove(5)
>>> s
{1, 2, 3, 4, 'hello', 8}

二.文件操作

1.open函数打开文件模式:

(1)r,只读模式

(2)w,只写模式:不可读,不存在则创建,存在则删除内容

(3)a,追加模式:可读,不存在则创建,存在则只追加内容

+标识可以同时写某个文件

2.关闭文件:

(1)close函数

(2)with:

>>> with open ("/root/1.txt","r") as f:
... f.readlines()
...
['this is a txt file line1 ', 'this is a txt file line2 ']

3.文件迭代器

1.使用方式:

>>> with open ("/root/1.txt","r") as f:
... f.readlines()
...
['this is a txt file line1 ', 'this is a txt file line2 ']
>>> with open ("/root/1.txt","r") as f:
... for line in f:
... print(line)
...
this is a txt file line1

this is a txt file line2

好处:避免readlines方法一次性读入文件至内存

三.函数

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

2.特性:

减少重复代码;使程序变得可扩展;使程序变得容易维护

3.作用域:函数内的变量不会影响与函数同级定义的变量的值,需要改变的话,需在函数内使用global声明

4.位置参数和关键字参数

a.关键字参数不能在位置参数之前

b.*args:

>>> def fun(*args):
... print(*args)
...
>>> fun("hello world",1,2)
hello world 1 2

接受任意多位置参数

c.**args:

>>> def fun(x,y,z=1,*args,**kwargs):
... print(x,y,z)
... print(args)
... print(kwargs)
...
>>> fun(1,2,3,4,5,6,foo="hello python!")
1 2 3
(4, 5, 6)
{'foo': 'hello python!'}
>>> fun(1,2)
1 2 1
()
{}

原文地址:https://www.cnblogs.com/raxxar/p/5759444.html