Python 杂记:内置函数(filter、map、sorted等)

注:本文仅列举了几个常用的内置函数,更多内置函数请参考官方文档:https://docs.python.org/3/library/functions.html

filter

函数原型:

filter(function, iterable)

示例:过滤掉偶数,只保留基数,代码如下:

foo = [1, 2, 3, 4, 5]
bar = filter(lambda x: True if x%2 else False, foo) # 相当于 perl 中的 @bar = grep { $_ % 2 } @foo
print bar   # [1, 3, 5]

map

perl 中 map() 方法可以用于对数组元素进行批量操作,例如:

my @foo = (1, 2, 3, 4, 5);
my @bar = map { $_ * 2 } @foo;  # (2, 4, 5, 8, 10)
my %qux = map { $_ => ($_ % 2 ? "odd" : "even") } @foo;
    # (1=>"odd", 2=>"even", 3=>"odd", 4=>"even", 5=>"odd")

python 中类似的实现如下:

foo = [1, 2, 3, 4, 5];
bar = map(lambda x: x*2, foo)   # [2, 4, 5, 8, 10]
qux = dict(map(lambda x: [x,"odd" if x%2 else "even"], foo))
    # {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}

Python 中 map() 可以传入多个序列参数,例如:

foo = [1, 3, 5, 7, 9];
bar = [2, 4, 6, 8, 10];
qux = map(lambda x,y: x+y, foo, bar) # [3, 7, 11, 15, 19]

reduce

示例:

foo = [1, 2, 3, 4, 5]
bar = reduce(lambda x,y: x+y, foo)
print bar   # 15,相当于执行了 (((1+2)+3)+4)+5

sorted

函数原型:

sorted(iterable, *, key=None, reverse=False)

其中:

  • key 参数用于指定一个函数,通过它来计算进行比较的目标值
  • reverse 参数用于控制“降序”还是“升序”排列(默认“升序”)

示例:假设有个学生信息列表,现在对他们按年龄进行排序,最终输出姓名列表,代码如下:

students = [
    { "name": "Jack",  "age": 23 },
    { "name": "Linda", "age": 21 },
    { "name": "Smith", "age": 22 },
    { "name": "Lucy",  "age": 21 },
    { "name": "Jason", "age": 22 },
]
names = map(
    lambda x: x["name"], 
    sorted(students, key = lambda s: s["age"])  # key 参数在 sorted() 中计算用于进行比较的目标
)
print(names)    # ['Linda', 'Lucy', 'Smith', 'Jason', 'Jack']

join

Python 中没有类似 perl 中的内置函数,不过可以通过字符串方法实现,例如:

students = ['Linda', 'Lucy', 'Smith', 'Jason', 'Jack']
names = ", ".join(students) # 返回一个字符串
print(names)    # Linda, Lucy, Smith, Jason, Jack

reversed

函数原型:

reversed(seq)

猜你喜欢

转载自www.cnblogs.com/itwhite/p/12340078.html
今日推荐