nested for loop

1 for a list of nested loop formula:

Examples are as follows:

li1 = range(1,6)
li2 = list("ABC")    # list("ABC") 的结果为 ["A", "B", "C"]    

for m in li1:
    for n in li2:
        print((m,n))

li = [(m,n) for m in li1 for n in li2]
print(li)


# 输出结果:
(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')
(4, 'A')
(4, 'B')
(4, 'C')
(5, 'A')
(5, 'B')
(5, 'C')
[(1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), (2, 'B'), (2, 'C'), (3, 'A'), (3, 'B'), (3, 'C'), (4, 'A'), (4, ' B ' ), (. 4, ' C ' ), (. 5, ' A ' ), (. 5, ' B ' ), (. 5, ' C ' )] 

# two cycles for the role list in quite formula to nested for loop

Reference Links:  https://www.jb51.net/article/150400.htm

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/neozheng/p/12008795.html