开发者

Convert C++ to Python (For Loop multiple assignment)

开发者 https://www.devze.com 2022-12-19 00:21 出处:网络
Convert to python: #include <iostream> using namespace std; int main(int argc, char** argv) { for (int i = 0, j = i + 3; i < 100; ++i, j= i+3)

Convert to python:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    for (int i = 0, j = i + 3; i < 100; ++i, j= i+3)
         cout << i << " j: " << j << endl;

    getchar();
    re开发者_运维问答turn 0;
}

I try:

for i in range(99):
    j = i + 3
    print i, " j: ", j

How to make it one for loop?


Just change 99 to 100

for i in range(100):
  j = i + 3
  print i, " j: ", j

Or

for i,j in [(i, i+3) for i in range(100)]:


These are identical except for the upper bound in the loop (98 vs 99). What is the question?

On one line (but please don't do this):

for i,j in [(i, i+3) for i in range(100)]:


Since j is always dependent on the value of i you may as well replace all instances of j with i + 3.


I dont get it, it is exactly one python for loop there. What is the question? Do you want the j declaration inside the loop declaration like in c++? Check Prasson'S answer for the closest python equivalent. But why have a j variable in the first place? j=i+3 seems to always be true, so why not this?

for i in range(100):
    print i, " j: ", i+3


for (i,j) in zip(range(100), range(3, 100+3)):


for i in range(100):
    j = i + 3
    print i, "j:", j
raw_input()

C++: http://ideone.com/7Kdmk

Python: http://ideone.com/nATEP

0

精彩评论

暂无评论...
验证码 换一张
取 消