Python中Collection的使用小技巧,pythoncollection
Python中Collection的使用小技巧,pythoncollection
本文所述实例来自独立软件开发者 Alex Marandon,在他的博客中曾介绍了数个关于 Python Collection 的实用小技巧,在此与大家分享。供大家学习借鉴之用。具体如下:
1.判断一个 list 是否为空
传统的方式:
if len(mylist): # Do something with my list else: # The list is empty
由于一个空 list 本身等同于 False,所以可以直接:
if mylist: # Do something with my list else: # The list is empty
2.遍历 list 的同时获取索引
传统的方式:
i = 0 for element in mylist: # Do something with i and element i += 1
这样更简洁些:
for i, element in enumerate(mylist): # Do something with i and element pass
3.list 排序
在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:
class Person(object): def __init__(self, age): self.age = age persons = [Person(age) for age in (14, 78, 42)]
传统的方式是:
def get_sort_key(element): return element.age for element in sorted(persons, key=get_sort_key): print "Age:", element.age
更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:
from operator import attrgetter for element in sorted(persons, key=attrgetter('age')): print "Age:", element.age
attrgetter 方法优先返回读取的属性值作为参数传递给 sorted 方法。operator 模块还包括 itemgetter 和 methodcaller 方法,作用如其字面含义。
4.在 Dictionary 中元素分组
和上面类似,先创建 Persons:
class Person(object): def __init__(self, age): self.age = age persons = [Person(age) for age in (78, 14, 78, 42, 14)]
如果现在我们要按照年龄分组的话,一种方法是使用 in 操作符:
persons_by_age = {} for person in persons: age = person.age if age in persons_by_age: persons_by_age[age].append(person) else: persons_by_age[age] = [person] assert len(persons_by_age[78]) == 2
相比较之下,使用 collections 模块中 defaultdict 方法的途径可读性更好:
from collections import defaultdict persons_by_age = defaultdict(list) for person in persons: persons_by_age[person.age].append(person)
defaultdict 将会利用接受的参数为每个不存在的 key 创建对应的值,这里我们传递的是 list,所以它将为每个 key 创建一个 list 类型的值。
本文示例仅为程序框架,具体功能还需要读者根据自身应用环境加以完善。希望本文所述实例对大家学习Python能起到一定的帮助作用。
使用python的正则表达式:
>>> a = '''\
... !!
... td:001
... tx:mmmm
... !!
... td:002
... tx:ooo
... '''
>>> print re.sub(r'(td:.*(\r?\n))', r'\1ad:0\2', a)
!!
td:001
ad:0
tx:mmmm
!!
td:002
ad:0
tx:ooo
=====不好意思没注意到是处理大文件===
text_process.py
---------------------------------------------------
#coding: utf-8
import os
f = open("source.txt", 'r')
f2 = open("data.txt", 'w')
for eachline in f:
f2.write(eachline)
if eachline.startswith("td:"):
f2.write("ad:0"+os.linesep)
f.close()
f2.close()
代码看起来没有问题。如果在python3上不能用,应该也只需要小小的调整。原则上应该跑得通。
不过话说回来,这样的技巧通常在python里用不上。因为python的强大并不是因为它的面向对象属性。
而且这些写代码的可读性也较差。 python的强大在于它通用,它与C的良好结合,最重要的是它是“脚本”。 可以动态的做任何事情,既然它的动态很强大,你就不需要写这样的代码。
直接这样
s1= AnyClass()
s1.any_variable = some_value
这样足够了。因为python可以自动给未知的变量,增加一个内部属性。所以我经常写下面的这样的代码
class Config: passconf = Config()conf.mysql_ip = "127.0.0.1"这样就可以了
相关内容
- Python采用raw_input读取输入值的方法,pythonraw_input
- python中enumerate的用法实例解析,pythonenumerate
- Python中正则表达式的用法实例汇总,python正则表达式
- Python使用函数默认值实现函数静态变量的方法,python默
- Python中多线程thread与threading的实现方法,pythonthreading
- Python中列表(list)操作方法汇总,pythonlist
- python调用Moxa PCOMM Lite通过串口Ymodem协议实现发送文件,
- Python异常处理总结,python异常处理
- 基于Python的身份证号码自动生成程序,python身份证号码
- 一个计算身份证号码校验位的Python小程序,python小程序
评论关闭