【Python Fennel Bean Series】Shooting list

【Python Fennel Bean Series】Shooting list

Programming in Python, using different methods to accomplish the same goal, is sometimes a very interesting thing. This reminds me of Kong Yiji in Lu Xun's works. Kong Yiji has done a lot of research on the four writing styles of fennel beans. I dare not compare myself to Kong Yiji, here are some Python fennel beans, for all coders.

Suppose there is a list: source_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]], and the list is required to be flattened into: [1, 2, 3, 4, 5, 6, 7, 8, 9].

Here we do a little preparatory work:

import functools
import itertools
import numpy
import operator

source_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]

Fennel beans one: for for

If you face this kind of problem for the first time, the first thing you may think of is for. The basic idea is as follows:

>>> flatten_list = []
>>> for sublist in source_list:
>>>    for item in sublist:
>>>        flatten_list.append(item)
>>> flatten_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Well, job done.

Of course, if you are familiar with list derivation, the above pile can be condensed into:

[item for sublist in source_list for item in sublist]

Fennel beans 2: sum

Python has a built-in function sum. This function is originally used to do arithmetic for us. It happens that lists can also be summed, so the following sentence can also be used:

sum(source_list, [])

Numpy also has a function of type sum , which has the same effect:

numpy.sum(numpy.array(source_list, dtype=object))

fennel bean 3: numpy

Numpy also has a professional tool for splicing arrays, which can be used to kill mosquitoes with a cannon:

list(numpy.concatenate(source_list))

fennel bean 4: numpy

Multiple items become one item, which makes me miss the benefits of reduce:

functools.reduce(lambda x,y: x+y, source_list)
functools.reduce(operator.concat, source_list)
functools.reduce(operator.iconcat, source_list, [])

Different paths lead to the same goal, and the above three statements achieve the same effect.

Fennel beans five: chain

When encountering problems with lists, experts will usually show the chain to distinguish them from ordinary experts:

list(itertools.chain(*source_list))
list(itertools.chain.from_iterable(source_list))

Fennel beans six: flatten

Finally, please don’t underestimate this problem. Anyone who plays with lists will probably encounter this problem one day, otherwise the senior experts would not have built so many wheels:

from pandas.core.common import flatten
list(flatten(source_list))

from matplotlib.cbook import flatten
list(flatten(source_list))

from setuptools.namespaces import flatten
list(flatten(source_list))

Guess you like

Origin blog.csdn.net/mouse2018/article/details/113529118