How to write a nested for loop as a single line by python
This article mainly describes how python will be nested for loop written in a single line, the article is very detailed, has a certain reference value, interested friends must read!
Write nested for loops as single lines
We often have nested for loop code like this
list1 = range(1,3) list2 = range(4,6) list3 = range(7,9) for item1 in list1: for item2 in list2: for item3 in list3: print(item1+item2+item3)
There are only three for loops here, and in actual coding, there may be more layers.
This code, readability is very poor, many people do not want to write this, but there is no better way to write.
Here's one of my favorite ways to use itertools library to achieve more elegant and readable code.
from itertools import product list1 = range(1,3) list2 = range(4,6) list3 = range(7,9) for item1,item2,item3 in product(list1, list2, list3): print(item1+item2+item3)
output is as follows
$ python demo.py 12 13 13 14 13 14 15 The above is "How python writes nested for loops as single lines" All the contents of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!