python - Python函数:'for'循环内的返回方法
问题描述
我有以下代码:
def encrypt(plaintext, k):
return "".join([alphabet[(alphabet.index(i)+k)] for i in plaintext.lower()])
我不明白python如何读取这种语法,有人可以在这里分解执行顺序吗?
我在python中经常遇到这种“单行”的写作风格,看起来总是那么优雅和高效,但我一直不明白其中的逻辑。
在此先感谢,祝您有美好的一天。
解决方案
在 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 的整个结果。
推荐阅读
- javascript - D3:如何使用点击文本的更新模式?
- python - BS4:删除标签
- debugging - 在连接的 Android 模拟器上运行调试应用程序需要很长时间,在 Visual Studio 上需要超过 10 分钟
- linux - QApplication 后清理
- swift - 如何以编程方式将约束添加到两个 UI 项(标签和按钮?
- wildfly - 如何为 elytron 生成掩码密码?
- node.js - NodeJS 创建函数数组并通过 async.series 执行
- c# - 如何在 Razor 视图中使用 foreach 循环显示连接的 sql 列值
- php - 向 loginController 添加逻辑
- math - 为什么 MAPLE 不评估我的方程中的积分和导数?