Python常用小技巧总结
本文实例总结了Python常用的小技巧。分享给大家供大家参考。具体分析如下:
1. 获取本地mac地址:
import uuid mac = 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 a print(a) # 此时a未定义
3. join 的使用
a = ['c','d'] a.reverse() a = ['d','c'] b = ','.join(a) print(b) # 输出 d,c
4. 随机数用法:
import random x = 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 string x= string.ascii_lowercase # print(x) # 输出: abcdefghijklmnopqrstuvwxyz d = 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程序设计有所帮助。