Python 等效于嵌套的 c++ 样式循环



在 c++ 中

for (auto i = min; i < sqrt_max; i++ ) {
for (auto  j = i; i*j <= sqrt_max; j++) {

我正在尝试在python中做完全相同的事情

for i in enumerate(range(min, sqrt_max  + 1)):
for j in enumerate(range(min, i * j < sqrt_max + 1)):

我得到undefined name j

  1. 不要在两个循环中使用enumerate(..)enumerate采用为其参数中的每个element返回一对index, element的东西。
  2. 您不能像这样使用j,因为它仅在 for 循环主体中定义。

你想要的是下面这样的东西:

for i in range(min, sqrt_max):  # i will not take the value of sqrt_max.
for j in range(i, 1 + sqrt_max//i):  # i is defined here within range, but j is not.
...

最新更新