小编Ehs*_*san的帖子

python中的for循环和zip

我有一个我正在尝试理解的代码,我需要帮助。

import numpy as np
Class_numbers=np.array(['a','b','c'])
students_per_class=np.array([10,20,30])
print("Students counts per class:\n{}".format(
{x: y for x, y in zip(Class_numbers, students_per_class)}))
Run Code Online (Sandbox Code Playgroud)

输出:

Students counts per class:
{'a': 10, 'b': 20, 'c': 30}
Run Code Online (Sandbox Code Playgroud)

我的理解:1-我们使用 {} 和 .format(...) 将 {} 替换为 ...

以下是我的问题:

Q1- 我不明白“对于 x, y in zip(Class_numbers, student_per_class)”。它像一个 2d for 循环吗?为什么我们需要拉链?我们可以有没有 zip 功能的 2d 循环吗?

Q2-我不明白 x:y 是如何工作的!编译器自动理解 x 和 y 的定义(在“x:y”中)在行的其余部分(例如 for 循环)中进行了描述?

PS:我是 MATLAB 专家,但我是 Python 新手,有时会很困惑!

埃桑

python zip for-loop

4
推荐指数
2
解决办法
2万
查看次数

标签 统计

for-loop ×1

python ×1

zip ×1