Using two for loops in python

I recently started learning Python and I had a question about loops hoping someone could answer. I want to be able to print all possible works from two numbers from one to ten. So: 2 on 2, 2 on 3, 2 on 4 ... 2 on 10, 3 on 2, 3 on 3 ... 3 on 10, 4 on 2, 4 on 3, etc. The easiest way to do this is to use two for loops, but I'm not sure. Can someone please tell me how this is done.

+4
source share
4 answers

Here is another way

a = [i*j for i in xrange(1,11) for j in xrange(i,11)]

note we need to run the second iterator with 'i' instead of 1, so this is doubly efficient

edit: , ,

b = []
for i in range(1,11):
    for j in range(1,11):
        b.append(i*j)

print set(a) == set(b)
+11

( SO itertools-addicted), :

from itertools import product
for i,j in product(xrange(1,11), xrange(1,11)):
    print i*j

: xrange, Hank Gay

+5
for i in range(1, 11):
    for j in range(1, 11):
        print i * j
+4

You may not need a nested solution for-loop.
One list comprehension loop (as shown below) will suffice:

r_list  = list(range(2, 11))   
output  = []
for m in r_list:
    tmp = [m*z for z in r_list]
    output.append(tmp)

print(output)

Or simply:

output  = []
for m in list(range(2, 11)):
    tmp = [m*z for z in list(range(2, 11))]
    output.append(tmp)

print(output)

Print

    [
        [4, 6, 8, 10, 12, 14, 16, 18, 20], 
        [6, 9, 12, 15, 18, 21, 24, 27, 30], 
        [8, 12, 16, 20, 24, 28, 32, 36, 40], 
        [10, 15, 20, 25, 30, 35, 40, 45, 50], 
        [12, 18, 24, 30, 36, 42, 48, 54, 60], 
        [14, 21, 28, 35, 42, 49, 56, 63, 70], 
        [16, 24, 32, 40, 48, 56, 64, 72, 80], 
        [18, 27, 36, 45, 54, 63, 72, 81, 90], 
        [20, 30, 40, 50, 60, 70, 80, 90, 100]
    ]
0
source

Source: https://habr.com/ru/post/1711087/


All Articles