Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How python forms a unified list without using any loops

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how python does not use any cycle to form a unified list, with a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Form a unified list without using any loops. Import itertoolstest = [[- 1,-2], [30, 40], [25, 35] print (list (itertools.chain.from_iterable (test) #-> [- 1,-2, 30, 40, 25, 35]

If you have an input list that contains nested lists or tuples as elements, use the following techniques. The limitation here, however, is that it uses for loops.

Def unifylist (l_input, l_target): for it in l_input: if isinstance (it, list): unifylist (it, l_target) elif isinstance (it, tuple): unifylist (list (it), l_target) else: l_target.append (it) return l_targettest = [- 1,-2], [1, 2], [4, (5) ]], (30,40), [25,35]] print (unifylist (test, [])) # Output = > [- 1,-2, 1, 2, 3, 4, 5, 6 jurisdiction 7, 30, 40, 25, 35]

An easier way to unify lists that contain lists and tuples is to use the Python

< more_itertools >

Bag. It doesn't need a loop. Just execute

< pip install more_itertools >

If not already.

Import more_itertoolstest = [[- 1,-2], [1, 2, 3, [4, (5, [6, 7])], (30, 40), [25, 35]] print (list (more_itertools.collapse (test) # Output= > [- 1,-2, 1, 2, 3, 4, 5, 6, 7, 30, 40, 25, 35] Thank you for reading this article carefully I hope the article "how to form a unified list of python without using any cycle" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report