3

Python代码阅读(第47篇):从列表右边开始执行给定函数

 2 years ago
source link: https://segmentfault.com/a/1190000041168911
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码

本篇阅读的代码实现了将给定的函数倒序依次应用在列表元素上的功能。

本篇阅读的代码片段来自于30-seconds-of-python

for_each_right

def for_each_right(itr, fn):
  for el in itr[::-1]:
    fn(el)

# EXAMPLES
for_each_right([1, 2, 3], print) # 3 2 1

for_each_right函数接收一个迭代列表和一个应用函数,返回将函数从右到左应用函数的结果。

函数使用for循环和列表切片itr[::-1]倒序遍历列表,在for循环体内,对每个列表元素应用函数fn


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK