[英]Why is my list not reiterating when I put a double loop on python
So I am trying to create a multiplication table from 2 to 9, for some reason when I put a double for loop it shows the following.所以我试图创建一个从 2 到 9 的乘法表,出于某种原因,当我放置一个double for 循环时,它显示以下内容。 I am thinking it's because, after the initial loop, the next loop simply starts at the [3] instead of [2].我认为这是因为,在初始循环之后,下一个循环只是从 [3] 而不是 [2] 开始。 Am I correct?我对么? if so, why is that?如果是这样,为什么会这样? I thought the iteration should start from [2] element on the second loop and go back to the first loop.我认为迭代应该从第二个循环的 [2] 元素开始,然后回到第一个循环。
numbers = map(int,range(2,10))
for numone in numbers:
for numtwo in numbers:
print('{0}*{1}={2}'.format(numone,numtwo,numone*numtwo))
Result
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
It's because when you use map
, you're using a iterator.这是因为当您使用map
,您正在使用迭代器。 And iterators only go forward.迭代器只会前进。 Ever.曾经。
There's no need for map
, you can just use range
:不需要map
,你可以只使用range
:
numbers = range(2,10)
for numone in numbers:
for numtwo in numbers:
print('{0}*{1}={2}'.format(numone,numtwo,numone*numtwo))
print()
The code above shows the expected output because range
is an iterable and can restart iteration.上面的代码显示了预期的输出,因为range
是可迭代的并且可以重新开始迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.