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 方法,作用如其字面含义。

评论关闭