首页 > 解决方案 > Python函数:'for'循环内的返回方法

问题描述

我有以下代码:

def encrypt(plaintext, k):
    return "".join([alphabet[(alphabet.index(i)+k)] for i in plaintext.lower()])

我不明白python如何读取这种语法,有人可以在这里分解执行顺序吗?

我在python中经常遇到这种“单行”的写作风格,看起来总是那么优雅和高效,但我一直不明白其中的逻辑。

在此先感谢,祝您有美好的一天。

标签: pythonfunctionfor-loop

解决方案


在 Python 中,我们称之为列表推导。还有其他广泛涵盖该主题的stackoverflow帖子,例如:“列表理解”是什么意思?它是如何工作的,我该如何使用它?解释嵌套列表理解的工作原理?.

在您的示例中,代码不完整,因此很难弄清楚“字母”或“明文”是什么。但是,让我们尝试分解它在高层次上的作用。

"".join([alphabet[(alphabet.index(i)+k)] for i in plaintext.lower()])

可以分解为:

"".join(  # The join method will stitch all the elements from the container (list) together
    [
        alphabet[alphabet.index(i) + k]  # alphabet seems to be a list, that we index increasingly by k
        for i in plaintext.lower()
        # we loop through each element in plaintext.lower() (notice the i is used in the alphabet[alphabet.index(i) + k])
    ]
)

请注意,我们可以将 for 理解重写为 for 循环。我创建了一个类似的示例,希望可以更好地说明问题:

alphabet = ['a', 'b', 'c']
some_list = []

for i in "ABC".lower():
    some_list.append(alphabet[alphabet.index(i)])  # 1 as a dummy variable

bringing_alphabet_back = "".join(some_list)
print(bringing_alphabet_back) # abc

最后,return只是返回结果。它类似于返回bring_alphabet_back 的整个结果。


推荐阅读