python的集合、遞迴、函數和模組

來源:互聯網
上載者:User

標籤:open   war   取值   start   元組   file   檔案   返回   1.2   

一、python的集合

集合具有天生去重和無序的特性,也由於無序,所以集合無法通過下標取值

建立一個集合的方法是:

  s = set()   #空集合

  s2 = {‘1‘,‘2‘,‘3‘}

添加元素的方法為:

  s.add(‘1‘)

刪除元素的方法為:

  s.remove(‘1‘)

  s.pop()    #隨機刪除一個值

  

s1 = {1,2,3}

s2 = {3,4,5}

交集:

s2.intersection(s2)

s2 & s1

並集:

s2.union(s1)

s2 | s1

差集(取s2裡不同於s1的值):

s2.difference(s1)

s3 - s2

 

二、python的遞迴

遞迴,也就是自己調用自己,最多能遞迴999次

count = 0
def test1():
num = int(input(‘please enter a number:‘))
global count
count+=1
num = 8
if num % 2 == 0: # 判斷輸入的數字是不是偶數
pass
print(count)
else:
    return test1() # 如果不是偶數的話繼續調用自己,輸入值
print(test1()) # 調用test

三、python函數
函數就是吧一堆程式碼群組合到一起,變成一個整體,將需多次重複的步驟整合成一個函數,可簡潔代碼,也可提高代碼的複用性
需要注意,函數不調用就不會被執行
函數中有全域變數和局部變數的區別,若函數內有局部變數,則定義變數需在調用變數前進行
def hello(file_name,content=‘‘): #形參,形式參數
#函數裡面的變數都是局部變數
f = open(file_name, ‘a+‘,encoding=‘utf-8‘)
if content:
f.write(content)
res = ‘‘
else:
f.seek(0)
res = f.read()
f.close()
return res
name = hello(‘aa.txt‘,‘kk‘)  #調用    #這裡的aa.txt,hhhh是實參
print(name)
上面file_name屬於位置參數,必填,而content由於已經設定了預設值,非必填
函數不是必須有傳回值,如果函數無傳回值則傳回值為None
函數中的return相當於迴圈裡的break,如果在函數中運行到return,則函數直接結束
除了位置參數,也存在可變參數,下面的args中形成的是元組

def test(a,b=1,*args):
print(a)
print(b)
print(args)

test(‘hh‘,2,‘kk‘,‘ss‘,‘ll‘)
test(a=5,b=10)
t = [1,2,3,4,5]
test(*t)

關鍵字參數是字典形式
def test2(a,**kwargs):
print(a)
print(kwargs)
test2(a=1,name=‘hhh‘,sex=‘female‘)

函數裡面的變數都是局部變數,若要修改全域變數,則在函數內變數前面需添加global

此處定義一個檢驗一個字串是否為合法的小數的函數
1、小數點的個數為1   2、按照小數點分割

def check_float(s):
s = str(s)
print(s)
if s.count(‘.‘)==1:
s_list = s.split(‘.‘)
#1.2 [1.2]
left = s_list[0]
right = s_list[1]
if left.isdigit() and right.isdigit():
return True
elif left.startswith(‘-‘) and left.count(‘-‘)==1 :
if left.split(‘-‘)[-1].isdigit() and right.isdigit():
return True
return False
print(check_float(‘+5.0‘))

四、python模組
python的模組共分為三種,
1、標準模組
  也就是python內建的,不需自己安裝
2、第三方模組
  需要安裝,是別人提供的
使用pip install xxx可自動安裝模組
手動安裝步驟:
# 首先下載安裝包
# 解壓
# 在命令列裡面進入到這個解壓之後的目錄
# 執行python setup.py install

3、自己寫的python檔案
  使用時若不在當前py檔案的目錄下則要添加環境變數
import xx來匯入一個檔案,匯入檔案的實質就是把這個檔案運行一遍

python的集合、遞迴、函數和模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.