简体   繁体   English

为什么当我在 python 上放置双循环时我的列表没有重复

[英]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.

相关问题 在文件中的空白行之后重复循环(Python) - Reiterating a loop after blank lines in file (Python) 如何防止我的python游戏重复执行,而是继续进行? - How can I prevent my python game from reiterating and instead carry on? 为什么退出while循环时列表消失了? - Why does my list disappear when I exit a while loop? Python:为什么当我将 int 或 list 或 tuple 放入列表时结果相同? - Python : why results are same when i put int or list or tuple in list? 为什么我的 python “循环”仅在我想从 url 列表中删除表并将它们转换为 df - Why does my python "loop for" only work on the last table when I want to scrap tables from list of urls and convert them to df 为什么我的代码可以在python shell中工作,但是当我双击py文件时却不能工作 - Why does my code work in python shell but not when I double click the py file 需要检查我的所有变量是否有 & - Need to check all my variables for an ampersand, I put variables in a list and check using a for loop, but Python only changes value inside list 为什么我的python程序双击.sh文件不运行 - Why does my python program not run when I double click the .sh file 为什么进入循环时我的列表没有变化? - Why my list is not changing when entering the loop? 在 Python 3 中将双循环转换为双列表理解? - Convert double for loop to double list comprehension in Python 3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM