Get the App
SLTechnology News&Howtos  ›  Development  › 

How to write a nested for loop as a single line by python

Shulou Source: shulou.com Published: 2022-06-01 05:26:13 11月09日 Update

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!

Tags: Loops code content writing articles elegance three value interest readability reality guys buddies regular meetings frequently used more knowledge coding industry information Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Apple MariaDB Microsoft NVidia