为什么for循环可以在列表内部工作

huangapple go评论67阅读模式
英文:

Why does a for loop work inside of a list

问题

我试图理解这行代码的工作原理,但没有成功。

x, y = [float(num) for num in input("输入一个点:").split(",")]

我尝试将这段代码分成几个部分,但这并没有解释这行代码的工作方式。

英文:

I'm trying to understand how this line of code works but to no luck.

x, y = [float(num) for num in input("Enter a point: ").split(",")]

I did try to split this code in sections but that didn't explain how this line of code worked

答案1

得分: 2

Sure, here's the code part you provided in Chinese:

tmp_list = []                     # 创建一个临时列表来保存分割的输入
point = input("输入一个点:")       # 获取数据
for num in point.split(","):       # 在逗号上分割字符串,然后迭代
    tmp_list.append(float(num))    # 将每个值转换为浮点数并添加到列表
x, y = tmp_list                   # 解包列表为x和y。这假设列表始终长度为2
del tmp_list                      # 删除临时列表
英文:

You could break the code out as (see comments):

tmp_list = []                     # create a temporary list to hold split input
point = input("Enter a point: ")  # get the data
for num in point.split(","):      # split string on comma then iterate
    tmp_list.append(float(num))   # make a float from each value and append to list
x, y = tmp_list                   # unpack list to x,y. This assumes list is always len 2
del tmp_list                      # delete temporary list

答案2

得分: 1

这是一种称为列表推导的方法。它在Python中用于缩短从另一个列表创建列表的代码。让我们一步一步来。

[float(num) for num in input("输入一个点:").split(",")]

首先,我们看到列表推导本身,作为for num in ...,但它正在迭代什么?它正在迭代一个输入函数,由逗号分隔。split方法将一个字符串按给定的分隔符拆分并返回一个列表。这就是在列表推导中进行迭代的内容。然后,代码将该字符串值转换为浮点数,然后通过解包返回的列表传递给x和y变量。

本质上,这是一种大量简化了@tdelaney答案中的代码的语法糖。

英文:

This is a method known as list comprehension. It is used in python to shorten code that creates a list from another list. Let's go step by step.

[float(num) for num in input("Enter a point: ").split(",")]

First, we see the comprehension itself, as for num in ..., but what is it iterating over? It iterates over an input function, split by a comma. The split method will split a string by the given seperator and return a list. This is what is being iterated over in the comprehension. The code then converts that string value into a float, before passing it on to the x and y variables by depacking the list returned

In essence, this is a lot of syntactic sugar that shortens the code in @tdelaney's answer

huangapple
  • 本文由 发表于 2023年5月21日 06:58:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定