python管理技巧_python 基础技巧

多个字典合并

>>> d1 = {'name' : 'revotu', 'age' : 99}>>> d2 = {'age' : 24, 'sex' : 'male'}#方法一

>>> from collections importChainMap>>> d =dict(ChainMap(d1, d2))#方法二

>>> d =dict(chain(d1.items(), d2.items()))#方法三

>>> d =d1.copy()>>> d.update(d2)

#方法四

>>> d = {**d1, **d2}

字符串分割

字符串分割的常用方法是直接调用字符串的str.split方法,但是其只能指定一种分隔符,如果想指定多个分隔符拆分字符串需要用到re.split方法(正则表达式的split方法)。

#语法:

re.split(pattern, string, maxsplit=0, flags=0)    #maxsplit为最大分割次数

#常规分割>>> importre>>> s = 'AAAA,BBBB:CCCC;DDDD'

>>> re.split(r'[,:;]', s)

['AAAA', 'BBBB', 'CCCC', 'DDDD']>>>

#指定分割次数,此时列表长度为maxsplit+1

>>> importre>>> s = 'AAAA,BBBB:CCCC;DDDD'

>>> re.split(r'[,:;]', s, 1)

['AAAA', 'BBBB:CCCC;DDDD']>>> re.split(r'[,:;]', s, 2)

['AAAA', 'BBBB', 'CCCC;DDDD']>>>

startswith()和endswith()参数可以是元组

# 常规写法

if image.endswith('.jpg') or image.endswith('.png') or image.endswith('.gif'):

pass

# 优化后写法

if image.endswith(('.jpg', '.png', '.gif')):

pass

# 常规写法

if url.startswith('http:') or url.startswith('https:') or url.startswith('ftp:'):

pass

# 优化后写法

if url.startswith(('http:', 'https:', 'ftp:')):

pass

enumerate()设置start参数做为索引起始值

# 常规写法,索引默认从0开始

for index, v in enumerate(data):

print(index+1, v)

# 优化后写法,索引默认从1开始

for index, v in enumerate(data, start=1):

print(index, v)

对切片命名

record = '....................100.................513.25......'

#常规写法

cost = int(record[20:23]) * float(record[40:46])# 优化后,通过内置的slice函数会创建一个切片对象,可以用在任何可以进行切片的地方

SHARES = slice(20, 23)

PRICE= slice(40, 46)

cost= int(record[SHARES]) * float(record[PRICE])

上下文管理器可以同时管理多个资源

#常规写法

with open('input.txt', 'r') as source:

with open('output.txt', 'w') as target:

target.write(source.read())#优化后

with open('input.txt', 'r') as source, open('output.txt', 'w') as target:

target.write(source.read())

else子句

Python中的else子句不仅能在if语句中使用,还能在for、while、和try语句中使用。在for循环或是while循环正常运行完毕时(而不是通过break语句或是return语句或是异常退出循环),才会运行else块

当try块中没有异常抛出时才运行else块

#正常没有 break和return语句

>> for i in range(3):

... print(i)

... else:

... print('Iterated over everything')

...

0

1

2Iterated over everything

# 加入break语句后else不执行>>> for i in range(3):

...if i == 2:

...break...print(i)

...else:

...print('Iterated over everything')

...

01

>>>

列表推导

示例一>>> symbols = '$¢£¥€¤'

>>> codes =[]>>> for symbol insymbols:

... codes.append(ord(symbol))

...>>>codes

[36, 162, 163, 165, 8364, 164]

示例二>>> symbols = '$¢£¥€¤'

>>> codes = [ord(symbol) for symbol insymbols]>>>codes

[36, 162, 163, 165, 8364, 164]

学会了列表推导的话, 示例二读起来更方便,Python 会忽略代码里 []、{} 和 () 中的换行,因此如果你的代码里有多行的列表、列表推导、生成器表达式、字典这一类的,可以省略不太好看的续行符 \。

通常的原则是,只用列表推导来创建新的列表,并且尽量保持简短。如果列表推导的代码超过了两行,你可能就要考虑是不是得用for循环重写了。

列表推导不会再有变量泄漏的问题(python3)

示例一>>> x = 'my precious'

>>> dummy = [x for x in 'ABC']>>> x'C'示例二>>> x = 'ABC'

>>> dummy = [ord(x) for x inx]>>>x'ABC'

>>>dummy

[65, 66, 67]

x 的值被保留了。

列表推导也创建了正确的列表

另一个示例

>>> colors = ['black', 'white']>>> sizes = ['S', 'M', 'L']>>> tshirts = [(color, size) for color in colors for size insizes]>>>tshirts

[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'),

('white', 'M'), ('white', 'L')]

②>>> for color incolors:

...for size insizes:

...print((color, size))

...

('black', 'S')

('black', 'M')

('black', 'L')

('white', 'S')

('white', 'M')

('white', 'L')>>> tshirts = [(color, size) for size insizes ➌

...for color incolors]>>>tshirts

[('black', 'S'), ('white', 'S'), ('black', 'M'), ('white', 'M'),

('black', 'L'), ('white', 'L')]

元组拆包

示例①>>> lax_coordinates = (33.9425, -118.408056)>>> latitude, longitude = lax_coordinates #元组拆包

>>>latitude33.9425

>>>longitude

示例②--用 * 运算符把一个可迭代对象拆开作为函数的参数:>>> divmod(20, 8)

(2, 4)>>> t = (20, 8)

>>> divmod(*t)

(2, 4)>>> quotient, remainder = divmod(*t)>>>quotient, remainder

(2, 4)

示例③---让一个函数可以用元组的形式返回多个值>>> importos>>>_, filename = os.path.split('/home/luciano/.ssh/idrsa.pub')>>>filename'idrsa.pub'在进行拆包的时候,我们不总是对元组里所有的数据都感兴趣,_ 占位符能帮助处理这种情况,

实例④--用**args获取不确定数量的元素>>> a, b, *rest = range(5)>>>a, b, rest

(0,1, [2, 3, 4])>>> a, b, *rest = range(3)>>>a, b, rest

(0,1, [2])>>> a, b, *rest = range(2)>>>a, b, rest

(0,1, [])

具名元组collections.namedtuple

示例

>>> from collections import namedtuple

>>> City = namedtuple('City', 'name country population coordinates') ➊

>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) ➋

>>> tokyo

City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722,

139.691667))

>>> tokyo.population ➌

36.933

>>> tokyo.coordinates

(35.689722, 139.691667)

>>> tokyo[1]

'JP'❶ 创建一个具名元组需要两个参数,一个是类名,另一个是类的各个字段的名字。后者可以是由数个字符串组成的可迭代对象,或者是由空格分隔开的字段名组成的字符串。

❷ 存放在对应字段里的数据要以一串参数的形式传入到构造函数中注意,元组的构造函数却只接受单一的可迭代对象)。

❸ 可以通过字段名或者位置来获取一个字段的信息。

具名元组的属性和方法

>>>City._fields ➊('name', 'country', 'population', 'coordinates')

>>> LatLong = namedtuple('LatLong', 'lat long')

>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))

>>> delhi = City._make(delhi_data) ➋

>>>delhi._asdict() ➌

OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population',

21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))])

>>> for key, value in delhi._asdict().items():

print(key + ':', value)

结果

name: Delhi NCR

country: IN

population:21.935coordinates: LatLong(lat=28.613889, long=77.208889)

❶ _fields 属性是一个包含这个类所有字段名称的元组。

❷ 用 _make() 通过接受一个可迭代对象来生成这个类的一个实例,它的作用跟 City(*delhi_data) 是一样的。

❸ _asdict() 把具名元组以 collections.OrderedDict 的形式返回,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值