问题描述
我有一段代码需要理解,我需要帮助.
I have a code that I am trying to understand and I need help.
import numpy as np
Class_numbers=np.array(['a','b','c'])
students_per_class=np.array([10,20,30])
print("Students counts per class:
{}".format(
{x: y for x, y in zip(Class_numbers, students_per_class)}))
输出:
Students counts per class:
{'a': 10, 'b': 20, 'c': 30}
我的理解:1- 我们使用 {} 和 .format(...) 将 {} 替换为 ...
What I understand:1- we use {} and .format(...) to replace {} with ...
这是我的问题:
Q1- 我不明白对于 x, y in zip(Class_numbers, Students_per_class)".它像一个 2d for 循环吗?为什么我们需要拉链?我们可以有没有 zip 功能的 2d 循环吗?
Q1- I do not understand "for x, y in zip(Class_numbers, students_per_class)". Is it like a 2d for loop? why we need the zip? Can we have 2d loop with out zip function?
Q2-我不明白 x:y 是如何工作的!编译器自动理解 x 和 y 的定义(在x:y"中)在该行的其余部分(例如 for 循环)中进行了描述?
Q2-I am not understanding how x:y works! the compile understand automatically that the definition of x and y (in "x:y") is described in the rest of the line(e.g. for loop)?
P.S:我是 MATLAB 专家,但我是 Python 新手,有时会很困惑!
P.S: I am expert in MATLAB but I am new to python and it is sometimes very confusing!
伊桑
推荐答案
Q1: zip
用于将 2 个列表合并在一起.它返回每个列表的第一个元素,然后是每个列表的第二个元素,依此类推.这是将两个列表视为键和数据以创建字典的技巧.
Q1: zip
is used to merge 2 lists together. It returns the first element of each list, then 2nd element of each list, etc. This is a trick to consider the two lists as key and data to create a dictionary.
Q2:这是一个字典(hash),使用了一种叫做dict comprehension"的方法.它创建显示为输出的字典.如果分配给变量 d
、d['a'] = 10
等
Q2: this is a dictionary (hash), using a method called "dict comprehension". It creates the dictionary shown as the output. If assigned to a variable d
, d['a'] = 10
, etc.
这篇关于python中的for循环和zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!