Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从PHP进行循环切换的Python_Python 3.x_For Loop - Fatal编程技术网

Python 3.x 从PHP进行循环切换的Python

Python 3.x 从PHP进行循环切换的Python,python-3.x,for-loop,Python 3.x,For Loop,我是python新手,通常使用PHP。有人能帮我清除python For循环的结构吗 numbers = int(x) for x in numbers 在PHP中,与For循环相关的所有内容都在主体内部使用。我不明白为什么python中的for循环前面有方法。首先,该语句缺少括号: numbers = [int(x) for x in numbers] 这称为a,相当于: numbers = [] for x in numbers: numbers.append(int(x)) d

我是python新手,通常使用PHP。有人能帮我清除python For循环的结构吗

numbers = int(x) for x in numbers

在PHP中,与For循环相关的所有内容都在主体内部使用。我不明白为什么python中的for循环前面有方法。

首先,该语句缺少括号:

numbers = [int(x) for x in numbers]
这称为a,相当于:

numbers = []
for x in numbers:
   numbers.append(int(x))
def numbers(N):
   for x in N:
      yield int(x)
请注意,您还可以将理解用作,在这种情况下,[]变成():

这相当于:

numbers = []
for x in numbers:
   numbers.append(int(x))
def numbers(N):
   for x in N:
      yield int(x)
这意味着for循环在处理时只执行一个
yield
。换句话说,当第一个示例在内存中构建一个列表时,生成器在执行时一次返回一个元素。这非常适合处理大型列表,您可以一次生成一个元素,而无需将所有内容都存储在内存中(例如,逐行处理文件)


因此,正如您所看到的,理解和生成器表达式是减少处理列表、元组和任何其他iterable所需代码量的好方法。

这不是for循环。但是当数字数组中没有条目时,它将如何遍历它?@user4833541:遍历0序列将遍历0次。如果
numbers
一开始是空的,它将不会执行
int(x)
语句(遍历空的iterable实际上是非操作)。