Python常用小技巧總結

來源:互聯網
上載者:User
本文執行個體總結了Python常用的小技巧。分享給大家供大家參考。具體分析如下:

1. 擷取本地mac地址:

import uuidmac = uuid.uuid1().hex[-12:]print(mac)

運行結果:e0cb4e077585

2. del 的使用

a = ['b','c','d']del a[0]print(a)# 輸出 ['c', 'd']

a = ['b','c','d']del a[0:2] # 刪除從第1個元素開始,到第2個元素print(a)# 輸出 ['d']

a = ['b','c','d']del aprint(a) # 此時a未定義

3. join 的使用

a = ['c','d']a.reverse()a = ['d','c']b = ','.join(a)print(b) # 輸出 d,c

4. 隨機數用法:

import randomx = random.randint(1,100)y = random.choice( 'abcd')print(x)print(y)

運行結果為:

68
b

5. dict 的使用:

a=[1,2,3]b=['a','b','c']c=dict(zip(a,b))print(c) # 輸出: {1:'a',2:'b',3:'c'}

6. map 的使用:

a='1-2-3-4'b=map(int,a.split('-'))print(b) # 輸出: [1,2,3,4]

7. [] 使用:

[].remove( value )
[].pop( index ) = value
[].count( x ) = x在列表中數量
{}使用
{}.pop( key ) = value
{}.get( key ) = value or {}.get( key ,0 ) 設預設值

8. 字串操作

a = str.decode( 'utf-8' )b = str.encode( 'utf-8' )str.isdigit() # 是否數值str1 = 'abc%s'%str2

9. 字串遍曆:

import stringx= string.ascii_lowercase# print(x) # 輸出: abcdefghijklmnopqrstuvwxyzd = enumerate( x )c = list( d )print(c)

輸出:

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')]

for i ,j in d:

此時:
i = 0,1,2,.....,25
j = 'a','b'......,'z'

希望本文所述對大家的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.