简体   繁体   English

python:对于In循环 - 我没有理解

[英]python: For In loops - i have no understanding

the resource i am using to learn python has you perform modules within its own website. 我用来学习python的资源让你在自己的网站上执行模块。 i think it was originally designed for students of this particular university so that is why i have tagged this with homework, even though it is not. 我认为它最初是为这所大学的学生设计的,所以这就是为什么我用家庭作业标记了这一点,尽管它不是。

anyway: 无论如何:

they had me perform this task: 他们让我执行这项任务:

Define a function prod(L) which returns the product of the elements in a list L. 定义一个函数prod(L),它返回列表L中元素的乘积。

i got this function to work using this code: 我使用此代码使此功能正常工作:

def prod(L):
   i = 0
   answer = 1
   x = len(L)
   while i < x:
    answer = answer * L[i]
    i = i + 1
    if i == x:
         return answer

the very next module talks very briefly about For-In loops. 下一个模块简要介绍了For-In循环。 and they pose the question: 他们提出了一个问题:

Define the function prod(L) as before, but this time using the new kind of loop. 像以前一样定义函数prod(L),但这次使用新类型的循环。

i have tried looking through other resources to understand how exactly to use this but i am not following anything. 我试过通过其他资源来了解如何使用这个,但我没有遵循任何事情。 can anybody explain, preferably in plain english, how a for-in loop works? 任何人都可以解释,最好用简单的英语解释for-in循环如何工作?

for reference: here is EVERYTHING that they talked about regarding the for-in loop 供参考:这里是他们谈到的关于for-in循环的一切

Looping through lists It is very common (like in the previous exercise) to loop through every value in a list. 循环遍历列表循环遍历列表中的每个值是非常常见的(如上一个练习中所示)。 Python allows a shortcut to perform this type of an operation, usually called a "for all" loop or a "for each" loop. Python允许快捷方式执行此类操作,通常称为“for all”循环或“for each”循环。 Specifically, when L is a list, this code 具体来说,当L是一个列表时,这个代码

for x in L: «loop body block»

does the following: first x is set to the first value in L and the body is executed; 执行以下操作:首先将x设置为L中的第一个值并执行正文; then x is set to the second value in L and the body is executed; 然后将x设置为L中的第二个值并执行正文; this is continued for all items in L. L中的所有项目都是如此。

i just cant fully wrap my head around this. 我只是无法完全包围这个。 im not looking for answers as i am doing this for knowledge growth - but i feel like im falling behind on this ): 我不是在寻找答案,因为我这样做是为了知识增长 - 但我觉得我落后于此):

Hopefully this simple example will help to clarify, the following two pieces of code do the same thing: 希望这个简单的例子有助于澄清,以下两段代码做同样的事情:

Using a while loop: 使用while循环:

L = ['a', 'b', 'c']
i = 0
while i < len(L):
    print L[i]
    i += 1

Using a for loop: 使用for循环:

L = ['a', 'b', 'c']
for c in L:
    print c

If you want the index AND the element like you have with a while loop, the pythonic way to do it is with enumerate: 如果你想要索引和像你一样的元素有一个while循环,pythonic的方法是使用枚举:

L = ['a', 'b', 'c']
for index, element in enumerate(L): # returns (0,'a'),(1,'b'),(2,'c')
    print index
    print element

As you can see above, the for loop lets you iterate directly over the contents of an iterable, as opposed to the while loop method where you keep track of an index and access items with the index. 正如您在上面所看到的, for循环允许您直接遍历iterable的内容,而不是while循环方法,您可以在其中跟踪索引并使用索引访问项目。

A for loop will loop through all of the contents of an iterable (usually a list) and perform an action against each member object, and then break out of the loop when there are no more objects to loop through. for循环将循环遍历iterable(通常是列表)的所有内容,并对每个成员对象执行操作,然后在没有更多对象循环时跳出循环。 Python standard docs explain this well: Python标准文档很好地解释了这一点:

http://docs.python.org/tutorial/controlflow.html#for-statements http://docs.python.org/tutorial/controlflow.html#for-statements

so for exaple the code 所以为了解释代码

for x in xrange(10):
    print x

will print the numbers 0 through 9 将打印数字0到9

In the explanation given, L is an iterable . 在给出的解释中, L可迭代的 This can be a sequence (eg list, tuple, string) or a generator (eg xrange() ). 这可以是序列(例如列表,元组,字符串)或生成器(例如xrange() )。 Each element of the iterable is bound to the name x in turn, and the loop body is executed. iterable的每个元素依次绑定名称 x ,并执行循环体。

In your first version, you defined an index variable i, then accessed L[i]. 在您的第一个版本中,您定义了索引变量i,然后访问了L [i]。 There's no other need for i, other than the if i == x return. 除了if i == x返回之外,我没有其他需要。

The "for x in sequence" idiom abstracts away the index variable. “for x in sequence”习语抽象出索引变量。 Instead of directly accessing L[i], you have a variable that will represent each item in L in a loop. 而不是直接访问L [i],你有一个变量代表循环中L中的每个项目。

So, let's say I have a list of 10 numbers (integers, let's say). 所以,假设我有一个包含10个数字的列表(整数,让我们说)。

A common task I might want to do would be to go through this list, and if the number is even, I add 10. 我可能想要做的一个常见任务是查看此列表,如果数字是偶数,我添加10。

So, if I input: [1, 2, 3, 4, 5] I would get: [1, 12, 3, 14, 5] 所以,如果我输入:[1,2,3,4,5]我会得到:[1,12,3,14,5]

One thing I could do is loop though, and for each index, check if the value at each index is even or odd. 我可以做的一件事就是循环,并且对于每个索引,检查每个索引的值是偶数还是奇数。

But, what if I don't want to think about indices? 但是,如果我不想考虑指数怎么办? I know I have to go through the entire list anyway, and I don't really need to know the index of the element for finding if the element is even or odd. 我知道无论如何我必须遍历整个列表,并且我真的不需要知道元素的索引来查找元素是偶数还是奇数。

So, instead of: 所以,而不是:

lst = [1, 2, 3, 4, 5]
newLst=[]
i=0
while i < 10:
    if (lst[i]%2==0): # if element i of lst is even
        newLst+= [ lst[i]+10 ]
    i+=1

I could just do: 我可以这样做:

for element in list:
    if(element%2==0):
        newLst+= [ element+10]
    else: newLst+= [element]

By doing this, I don't have to worry about indices, and I know element will be one item from the list. 通过这样做,我不必担心索引,我知道element将是列表中的一个项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM