在python中进行循环和压缩 [英] For loop and zip in python

查看:100
本文介绍了在python中进行循环和压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想理解的代码,我需要帮助.

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:\n{}".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-我不理解对于zip中的x,y(类别编号,学生类别)".像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!

Ehsan

推荐答案

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:这是一个字典(哈希),使用一种称为"dict comprehension"的方法.它创建显示为输出的字典.如果分配给变量dd['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中进行循环和压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆