简体   繁体   English

在for循环或while循环中使用列表

[英]using lists in a for loop or while loop

so there is something I don't understand about these two loops 所以对于这两个循环我有些不了解

If I have a list called numbers 如果我有一个叫数字的清单

to find the largest number using a for loop I can: 使用for循环查找最大的数字,我可以:

for number in numbers:

    if number > largest:

        largest = number

but why doesn't: 但是为什么不:

 if number[index] > largest:

     largest = number[index]

work? 工作?

and it is the opposite for while loops, so if I want to do something to a list, for example 而while循环则相反,因此,例如,如果我想对列表做一些事情

to replace a value with another, number[index] works and number doesnt work. 用另一个替换值, number[index]有效,number不起作用。

Because you're already going through each element in the list, not the actual list itself. 因为您已经遍历了列表中的每个元素,而不是实际的列表本身。 Thus, you don't need to have the index and access the same element you're already looping with. 因此,您无需具有索引并访问已循环使用的相同元素。

>>> for i in range(5):
...     print i
... 
0
1
2
3
4

See how i is not the list but just an individual element in the list? 看看i不是列表,而是列表中的单个元素吗? Doing number[index] is just pointless :p number[index]是没有意义的:p

If you want indexes, you can use enumerate : 如果需要索引,可以使用enumerate

>>> L = ['one', 'two', 'three']
>>> for i, j in enumerate(L):
...     print i, j, L[i]
... 
0 one one
1 two two
2 three three

As for while loops, well, this isn't the circumstance where you would use one. 至于while循环,好吧,这不是您要使用的情况。 Use a for-loop ;). 使用for循环;)。

for number in numbers assign the elements to number one by one. for number in numbers将元素逐一分配。 So number here is an element of numbers . 因此, number这里的元素numbers If number is really a number. 如果number真的是数字。 There will be an error using number[i] . 使用number[i]会出错。 This is a syntax of Python. 这是Python的语法。 But not for while . 但不适合while You have to use index to access the elements in the list. 您必须使用索引来访问列表中的元素。

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

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