【发布时间】:2020-04-10 13:19:48
【问题描述】:
我目前正在学习 Python,因为我正在学习数据挖掘课程。 我正在制作一个 for 循环来制作一个嘈杂的数据文件来进行平滑处理,我发现 Python for 循环有一个我无法理解也无法绕过的特性。
所以我做了这个简单的测试 C++ 和 Python 代码。 C++ 一个可以工作,但 Python 一个不行。
原因是 C++ 允许在 for 循环块中对计数器变量 i 进行任意更新,但 Python 不允许。
在 Python 代码中,我尝试通过在 while 循环中执行 i += 1 来任意更新 i,但如果您查看 At the first part of the loop, i = SOMETHING 的输出,Python 正在任意更新 i 仅在 for 循环中的 while 循环中,但在退出该 while 循环时将值恢复回来。
(输出在底部的 cmets 中)
这是为什么呢?是范围问题吗? (C++ 和 Python 都是静态作用域的) 是因为他们的类型吗? (我只熟悉 C++ 和 Java 等静态类型语言,不熟悉 Python 等动态类型语言)
在 Python 上,似乎 for 循环实际上是一个具有按值返回参数的函数 i,它忽略了函数内部发生的参数上的所有更改。
我试过了:
- 将计数器 i 设置为全局变量。
- 使用
range(0, len(input), *variable*),但我仍然无法复制它。 - 研究是否可以通过在 Python 上使用静态变量或类似排序来解决(我认为这无关紧要?)
在 Python 上,您将如何复制此 C++ 代码? 你能告诉我为什么这些 for 循环的行为不同吗?谢谢。
这是正常工作的 C++ 代码:
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string input = "abc defg";
string eachWord = "";
for(int i = 0; i < input.length(); i++)
{
cout << "At the first part of the loop, i = " << i << " ." << endl;
while(input[i] != ' ' && input[i] != '\0')
{
eachWord += input[i];
i++;
}
cout << eachWord << endl;
cout << "At the last part of the loop, i = " << i << " ." << endl << endl;
eachWord = "";
}
}
/*
Output:
At the first part of the loop, i = 0 .
abc
At the last part of the loop, i = 3 .
At the first part of the loop, i = 4 .
defg
At the last part of the loop, i = 8 .
*/
这是无法正常工作的 Python 代码,我试图复制 C++ 代码:
input = "abc defg"
eachWord = ''
for i in range(len(input)):
print("At the first part of the loop, i = ", i, ".")
while(input[i] != ' ' and input[i] != '\0'):
eachWord += input[i]
i += 1
print(eachWord)
print("At the last part of the loop, i = ", i, ".")
print()
eachWord = ''
"""
Output:
At the first part of the loop, i = 0 .
abc
At the last part of the loop, i = 3 .
At the first part of the loop, i = 1 .
bc
At the last part of the loop, i = 3 .
At the first part of the loop, i = 2 .
c
At the last part of the loop, i = 3 .
At the first part of the loop, i = 3 .
At the last part of the loop, i = 3 .
At the first part of the loop, i = 4 .
Traceback (most recent call last):
File "main.py", line 6, in <module>
while(input[i] != ' ' and input[i] != '\0'):
IndexError: string index out of range
"""
【问题讨论】:
-
maxLen = len(input)然后i = 0然后while i < maxLen:并在循环结束时i+=1 -
我认为您不应该在 Python 中复制您的 c++ 代码。 Python 风格不同,应该以不同的方式处理。例如:对于您的示例,您可以编写更多的一行/pythonic 代码。
-
“在 Python 上,for 循环似乎实际上是一个具有按值返回参数 i 的函数,它忽略了函数内部发生的参数上的所有更改。”这与实际发生的事情相差不远。在
for循环的每次迭代中,i确实被range(len(input))的下一个值替换,而不管循环体中的i发生了什么。 -
如果你想拆分成单词,那么你只需要
"abc defg".split(),你不需要创建所有的循环。 -
谢谢你们!我只是“假设”不同语言的所有 for 循环都应该表现相同。