简体   繁体   中英

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. I am thinking it's because, after the initial loop, the next loop simply starts at the [3] instead of [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.

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. And iterators only go forward. Ever.

There's no need for map , you can just use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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