How python forms a unified list without using any loops
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!