python學習筆記3 集合,檔案操作,函式

2022-08-12 00:36:20 字數 1781 閱讀 4346

一.集合

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

>>> s

集合可以理解為有鍵沒有值的字典,鍵之間去重,無序。

2.集合操作:

>>> s1=

>>> s2=

>>> s1&s2

//交集

>>> s1|s2

//並集

>>> s1^s2

//差集

3.新增和刪除元素

>>> s=set([1,2,3,4,5,5,5,8])

>>> s

>>> s.add('hello')

>>> s

>>> s.remove(5)

>>> s

二.檔案操作

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\n', 'this is a txt file line2\n']

3.檔案迭代器

1.使用方式:

>>> with open ("/root/1.txt","r") as f:

... f.readlines()

...

['this is a txt file line1\n', 'this is a txt file line2\n']

>>> 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)

>>> fun(1,2)

1 2 1

(){}

python3集合 Python3 集合

集合 set 是乙個無序的不重複元素序列。可以使用大括號 或者 set 函式建立集合,注意 建立乙個空集合必須用 set 而不是 因為 是用來建立乙個空字典。建立格式 parame 或者set value 這裡演示的是去重功能 orange in basket 快速判斷元素是否在集合內 true c...

python3集合 Python3 集合

python3 集合 集合 set 是乙個無序的不重複元素序列。可以使用大括號或者set 函式建立集合,注意 建立乙個空集合必須用set 而不是,因為是用來建立乙個空字典。集合內建方法 add 為集合新增元素 例項 fruits.add orange print fruits 輸出結果為 clear...

Python學習筆記 七 集合

集合 set 是乙個無序的不重複元素序列。建立格式 parame 或者set value print basket 這裡演示的是去重功能 orange in basket 快速判斷元素是否在集合內 true crabgrass in basket false 下面展示兩個集合間的運算.a set a...