Python中Collection的使用小技巧

yipeiwu_com6年前Python基础

本文所述实例来自独立软件开发者 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五子棋游戏的设计与实现

这个python的小案例是五子棋游戏的实现,在这个案例中,我们可以实现五子棋游戏的两个玩家在指定的位置落子,画出落子后的棋盘,并且根据函数判断出输赢的功能。 这个案例的思路如下所示: 首...

简单了解python单例模式的几种写法

方法一:使用装饰器 装饰器维护一个字典对象instances,缓存了所有单例类,只要单例不存在则创建,已经存在直接返回该实例对象。 def singleton(cls): inst...

Python实现命令行通讯录实例教程

Python实现命令行通讯录实例教程

1、实现目标 编写一个命令行通讯录程序,可以添加、查询、删除通讯录好友及电话 2、实现方法 创建一个类来表示一个人的信息。使用字典存储每个人的对象,名字作为键。 使用pickle模块...

Windows8下安装Python的BeautifulSoup

运行环境:Windows 8.1 Python:2.7.6 在安装的时候,我使用的pip来进行安装,命令如下: 复制代码 代码如下: pip install beautifulsoup4...

分享6个隐藏的python功能

小编在以前给大家介绍过python一些很少用到的功能,这次我们给大家分享了6个隐藏的python功能,学习下。 在python的设计哲学中,有这么一条内容:“Simple is bett...