Python中的for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4170656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:36:39  来源:igfitidea点击:

for loop in Python

python

提问by newprint

In C/C++, I can have the following loop

在 C/C++ 中,我可以有以下循环

for(int k = 1; k <= c ; k +=2)

How do the same thing in Python?

在 Python 中如何做同样的事情?

I can do this

我可以做这个

for k in range(1,c):

In Python, which would be identical to

在 Python 中,这将等同于

for(int k = 1; k <= c ; k++)

in C/C++.

在 C/C++ 中。

采纳答案by bukzor

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

您还应该知道,在 Python 中,对整数索引进行迭代是不好的风格,而且比替代方法慢。如果您只想查看列表或字典中的每个项目,请直接遍历列表或字典。

mylist = [1,2,3]
for item in mylist:
    print item

mydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
    print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous ivariable.

这实际上比将上面的代码与 range() 一起使用更快,并删除了无关i变量。

If you need to edit items of a list in-place, then you doneed the index, but there's still a better way:

如果您需要就地编辑列表的项目,那么您确实需要索引,但还有更好的方法:

for i, item in enumerate(mylist):
    mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

同样,这既更快又被认为更具可读性。这是从 C++ 到 Python 时需要进行的主要思想转变之一。

回答by carlosdc

Try using this:

尝试使用这个:

for k in range(1,c+1,2):

回答by Pir Fahim Shah

If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it'll work a lot

如果你想在 Python 中编写一个循环来打印一些整数 no 等,那么只需复制并粘贴这段代码,它会工作很多

# Display Value from 1 TO 3  
for i in range(1,4):
    print "",i,"value of loop"

# Loop for dictionary data type
  mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA"  }  
  for user, country in mydata.iteritems():
    print user, "belongs to " ,country

回答by Francisco Manuel Garca Botella

The answer is good, but for the people that want this with range(), the form to do is:

答案是好的,但是对于想要使用 的人来说,要做range()的形式是:

range(end):

range(end)

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start,end):

range(start,end)

 >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start,end, step):

range(start,end, step)

 >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

回答by Octane

In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.

在 Python 中,您通常使用 for in 循环,而不是像 C/C++ 这样的通用 for 循环,但您可以使用以下代码实现相同的目的。

for k in range(1, c+1, 2):
  do something with k

Reference Loop in Python.

Python 中的参考循环。

回答by iNet

In C/C++, we can do the following, as you mentioned

在 C/C++ 中,我们可以执行以下操作,正如您提到的

for(int k = 1; k <= c ; k++)
for(int k = 1; k <= c ; k +=2)

We know that here kstarts with 1 and go till (predefined) cwith step value 1 or 2 gradually. We can do this in Python by following,

我们知道这里k从 1 开始并c逐渐以步长值 1 或 2直到(预定义)。我们可以通过以下方式在 Python 中做到这一点,

for k in range(1,c+1):
for k in range(1,c+1,2):

Check thisfor more in depth.

检查这个更深入。

回答by lukaslanger

Use this instead of a for loop:

使用它而不是 for 循环:

k = 1
while k <= c:
   #code
   k += 1

回答by hyder47

The range() function in python is a way to generate a sequence. Sequences are objects that can be indexed, like lists, strings, and tuples. An easy way to check for a sequence is to try retrieve indexed elements from them. It can also be checked using the Sequence Abstract Base Class(ABC) from the collections module.

python中的range()函数是一种生成序列的方法。序列是可以被索引的对象,如列表、字符串和元组。检查序列的一种简单方法是尝试从中检索索引元素。也可以使用集合模块中的序列抽象基类(ABC)来检查它。

from collections import Sequence as sq
isinstance(foo, sq)

The range() takes three arguments start, stop and step.

range() 接受三个参数 start、stop 和 step。

  1. start : The staring element of the required sequence
  2. stop : (n+1)th element of the required sequence
  3. step : The required gap between the elements of the sequence. It is an optional parameter that defaults to 1.
  1. start : 所需序列的起始元素
  2. stop : 所需序列的第 (n+1) 个元素
  3. step :序列元素之间所需的间隙。它是一个可选参数,默认为 1。

To get your desired result you can make use of the below syntax.

要获得所需的结果,您可以使用以下语法。

range(1,c+1,2)