[Python] More Pythonic lists are merged with the Amway and pythonpythonic of Python.
Original question: https://segmentfault.com/q/1010000005904259
Question: How can I combine a list like L = [1, 2, 3], [4, 5, 6], [7, 8, 9] into a list like [1, 2, 3, 4, 5, 6, 7, 8, 9?
The most direct method (By: pine forest)
ret = []for x in L: ret += xprint(x)
Use the itertools module (By: dokelung) in the standard library)
from itertools import chainlst = list(chain(*L))
This method is provided by the standard library, which is obviously more efficient and concise.
Note: * operators are used to unpack a parameter list.
Is there a more Pythonic method that does not use the standard library?
The answer is yes, of course. We can use List Comprehension, which is a very useful technique in python.
myList = [x for j in L for x in j]
Summary
Among the three solutions, method 1 is the most direct solution, and method 2 uses the existing standard library, which generally provides better efficiency.
Method 3 is to give full play to the advantages of Python. After all, Pythonic is the goal of every Python programmer and is also an attractive place for this language.
In fact, this article mainly introduced the Python of Amway. A piece of Pythonic code is very entertaining. Python also provides many Pythonic features.
For example, the LIst Comprehension method mentioned above is used to construct a sequence (LIst, tuples, dictionary). to implement it in other languages, lambda expressions are generally used,
Specifically, lambda expressions are excluded. In terms of readability, it is not as good as defining functions directly, but also lacks the beauty of symmetry.
For example, Slice in Python is also a very useful and elegant technique.
The most classic string inversion, which can be written in python.
S = "Hello, World! "Print (s [:-1]) # For details, refer to the python documentation. Here we use the step size of-1.
Interval sampling can be written like this
L = [1, 2, 3, 4, 5...] print (L [: 3]) #3 indicates the step length, which can be, 7 ....