非常实用的Python小技巧总结


本文摘自php中文网,作者伊谢尔伦,侵删。

这篇文章主要介绍了Python常用小技巧,实例总结了Python关于字典、字符串、随机数等操作技巧,非常简单实用,需要的朋友可以参考下

本文实例总结了Python常用的小技巧。分享给大家供大家参考。具体分析如下:

1. 获取本地mac地址:


1

2

3

import uuid

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

print(mac)

运行结果:e0cb4e077585

2. del 的使用


1

2

3

a = ['b','c','d']

del a[0]

print(a)# 输出 ['c', 'd']


1

2

3

a = ['b','c','d']

del a[0:2] # 删除从第1个元素开始,到第2个元素

print(a)# 输出 ['d']


1

2

3

a = ['b','c','d']

del a

print(a) # 此时a未定义

3. join 的使用


1

2

3

4

5

a = ['c','d']

a.reverse()

a = ['d','c']

b = ','.join(a)

print(b) # 输出 d,c

4. 随机数用法:


1

2

3

4

5

import random

x = random.randint(1,100)

y = random.choice( 'abcd')

print(x)

print(y)

运行结果为:

68
b

5. dict 的使用:


1

2

3

4

a=[1,2,3]

b=['a','b','c']

c=dict(zip(a,b))

print(c) # 输出: {1:'a',2:'b',3:'c'}

6. map 的使用:


1

2

3

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. 字符串操作


1

2

3

4

a = str.decode( 'utf-8' )

b = str.encode( 'utf-8' )

str.isdigit() # 是否数值

str1 = 'abc%s'%str2

9. 字符串遍历:


1

2

3

4

5

6

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小技巧总结的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

如何使用vscode愉快的写Python于调试配置步骤_Python

详解Python的基本数据类型

关于Python如何操作消息队列(rabbitmq)的方法教程

Python中怎么向字典添加元素

Python tkinter实现剪刀石头布小游戏

讲解Python 中删除文件的几种方法

介绍Python应用学习之qrcode生成二维码

Python合法标识符的命名规范是什么

Python怎么导入math库?

为什么黑客都使用Python

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...