In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.