挑战在代码里面不写for循环,让代码变得更简洁、规范、结构化,以及更好的代码可读性!

挑战在代码里面不写for循环,让代码变得更简洁、规范、结构化,以及更好的代码可读性!
兄弟们,你们好,这是新的一天!你今天打到密码了吗?
[En]

Hello, brothers, it’s a new day! Did you hit the code today?

; 一、序言

为什么要挑战自己在代码里不写 for loop?因为这样可以迫使你去学习使用比较高级、比较地道的语法或 library。文中以 python 为例子,讲了不少大家其实在别人的代码里都见过、但自己很少用的语法。

自从我开始探索 Python 中惊人的语言功能已经有一段时间了。一开始,我给自己一个挑战,目的是让我练习更多的 Python 语言功能,而不是使用其他编程语言的编程经验。这让事情变得越来越有趣!代码变得越来越简洁,代码看起来更加结构化和规范化。下面我将会介绍这些好处。

二、正文

通常如下使用场景中会用到 for 循环:

  • 按顺序提取一些信息
    [En]

    extract some information in a sequence*

  • 从一个序列生成另一个序列
    [En]

    generate one sequence from another*

  • 写 for 已成习惯

幸运的是,Python 已经有很多工具可以帮助你完成这些工作,你只需要转移你的思路,并以不同的角度来思考它。

通过避免编写 for 循环,你可以获得什么好处:

  • 较少的代码量
  • 更好的代码可读性
  • 更少的缩进(对 Python 还是很有意义的)

让我们来看看下面的代码结构:

[En]

Let’s take a look at the following code structure:

1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:

学习中遇到问题没人解答?小编创建了一个Python学习交流基地,点击蓝色字体即可,寻找有志同道合的小伙伴,互帮互助,这里还有不错的视频学习教程和PDF电子书

在这个例子中,我们正在处理多层嵌套的代码,这很难阅读。这个例子使用了多层嵌套的代码。我在这段代码中发现它无差别使用缩进把管理逻辑(with, try-except)和业务逻辑(for, if)混在一起。如果你遵守只对管理逻辑使用缩进的规范,那么核心业务逻辑应该立刻脱离出来。

“扁平结构比嵌套结构更好” – The Zen of Python

可以使用的已有的工具来替换 for 循环

1.List Comprehension / Generator 表达式

让我们来看一个简单的例子。如果要将一个数组转换为另一个数组:

[En]

Let’s look at a simple example. If you want to convert one array to another:

result = []
for item in item_list:
    new_item = do_something_with(item)
    result.append(item)
#Python学习交流群:279199867

如果你喜欢 MapReduce,你也可以使用 map,或者 Python 中的 List Comprehension:

result = [do_something_with(item) for item in item_list]

同样,如果您只想迭代数组中的元素,也可以使用一样的代码 Generator Expression。result = (do_something_with(item) for item in item_list)

2.函数

如果您想要将一个数组映射成另外数组,只需调用 map 函数,就可以用一个更高级、更实用的编程方式解决这个问题。

doubled_list = map(lambda x: x * 2, old_list)

如果要将序列减少为单个,请使用 reduce

from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)

另外,许多 Python 内置函数都会使用 iterables:

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> all(a)
False
>>> any(a)
True
>>> max(a)
9
>>> min(a)
0
>>> list(filter(bool, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> dict(zip(a,a))
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
>>> sorted(a, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> str(a)
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
>>> sum(a)
45

3.Extract Functions or Generators

以上两种方法适用于处理更简单的逻辑。更复杂的逻辑呢?作为程序员,我们编写函数来提取复杂的业务。同样的想法也适用于这里。如果这是你写的:

[En]

The above two methods are good for dealing with simpler logic. How about more complex logic? As programmers, we write functions to extract complex business. The same idea applies here. If this is what you wrote:

results = []
for item in item_list:
    # setups
    # condition
    # processing
    # calculation
    results.append(result)

显然,您在代码块中添加了太多的责任。相反,我建议你这样做:

[En]

Obviously you add too much responsibility to a code block. Instead, I suggest you do:

def process_item(item):
    # setups
    # condition
    # processing
    # calculation
    return result

results = [process_item(item) for item in item_list]

如果换成嵌套函数会如何

results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))

换成 List Comprehension 来实现是这样的:

results = [(i, j)
           for i in range(10)
           for j in range(i)]

如果代码块需要记录一些内部状态

[En]

If your code block needs to record some internal state

finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
    current_max = max(i, current_max)
    results.append(current_max)

results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

我们使用 generator 来实现这一点:

def max_generator(numbers):
    current_max = 0
    for i in numbers:
        current_max = max(i, current_max)
        yield current_max

a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = list(max_generator(a))

读者可能要问 “等等!你在 generator 中用到 for 循环,作弊啊!别急,再看看下面的代码。

不要自己写,itertools 会帮你实现了。

这个模块很简单。我相信这个模块在大多数场景中可以替换你原先的 for 循环。例如,最后一个例子可以重写为:

from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))

另外,如果要迭代组合序列,则需要使用product(), permutations(), combinations()。

三、结论

  • 在大多数情况下,您都不需要编写 for 循环。
  • 你应该避免编写 for 循环,这样会有更好的代码可读性。

好了,我的兄弟,今天的分享就到这里。我想推荐一组爬虫视频,涵盖90%的常见案例。我希望它能对你有所帮助!

[En]

All right, my brother, that’s all for today’s sharing. I’d like to recommend a set of crawler videos, covering 90% of common cases. I hope it will be helpful to you!

爬虫:Python爬虫入门到精通100集实战

Original: https://www.cnblogs.com/hahaa/p/16573889.html
Author: 轻松学Python
Title: 挑战在代码里面不写for循环,让代码变得更简洁、规范、结构化,以及更好的代码可读性!

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498837/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球