python list使用技巧总结,pythonlist使用技巧,判断一个 list 是否
python list使用技巧总结,pythonlist使用技巧,判断一个 list 是否
判断一个 list 是否为空
传统的方式:
if len(mylist): # Do something with my listelse: # The list is empty
由于一个空 list 本身等同于 False,所以可以直接:
if mylist: # Do something with my listelse: # The list is empty
遍历 list 的同时获取索引
传统的方式:
i = 0for element in mylist: # Do something with i and element i += 1
这样更简洁些:
for i, element in enumerate(mylist): # Do something with i and element pass
list 排序
在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:
class Person(object): def __init__(self, age): self.age = agepersons = [Person(age) for age in (14, 78, 42)]
传统的方式是:
def get_sort_key(element): return element.agefor element in sorted(persons, key=get_sort_key): print "Age:", element.age
更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:
from operator import attrgetterfor element in sorted(persons, key=attrgetter('age')): print "Age:", element.age
attrgetter 方法优先返回读取的属性值作为参数传递给 sorted 方法。operator 模块还包括 itemgetter 和 methodcaller 方法,作用如其字面含义。
相关内容
- python dict使用技巧,pythondict,在 Dictionary
- Python统计列表中元素出现的次数,python统计列表元素
- Python yield使用示例,pythonyield示例,下面2段代码通过Py
- python使用eval,exec将字符串(string)转为字典(dict),pythone
- Python POP3 收取邮件,pythonpop3,python 为我们提供
- python爬虫抓网页的总结,python爬虫抓,学用python也有3个
- python核心模块之pickle和cPickle的使用示例,picklecpickle,
- Python使用ConfigParser读写ini配置文件,,ini文件格式概述
- Python读取纯真IP数据库,pythonip数据库,纯真IP数据库可谓
- python求两序列的和最小差值序列,python最小差值序列
评论关闭