【Python茴香豆系列】之 拍扁列表#

用 Python 编程,使用不同的方法来完成同一个目标,有时候是一件很有意思的事情。这让我想起鲁迅笔下的孔乙己。孔乙己对于茴香豆的茴字的四种写法颇有研究。我不敢自比孔乙己,这里搜集一些 Python 的茴香豆,以飨各位码农。

假设有一个列表:source_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] ,要求把这个列表拍扁,变成:[1, 2, 3, 4, 5, 6, 7, 8, 9]

[1]:
import functools
import itertools
import numpy
import operator

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

茴香豆一: for for#

[2]:
flatten_list = []
for sublist in source_list:
    for item in sublist:
        flatten_list.append(item)
flatten_list
[2]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[3]:
[item for sublist in source_list for item in sublist]
[3]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[4]:
sum(source_list, [])
[4]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[5]:
functools.reduce(operator.concat, source_list)
[5]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[6]:
functools.reduce(lambda x,y: x+y, source_list)
[6]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[7]:
functools.reduce(operator.iconcat, source_list, [])
[7]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[8]:
list(itertools.chain(*source_list))
[8]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9]:
list(itertools.chain.from_iterable(source_list))
[9]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[10]:
list(numpy.concatenate(source_list))
[10]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[11]:
from pandas.core.common import flatten
list(flatten(source_list))
[11]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[12]:
from matplotlib.cbook import flatten
list(flatten(source_list))
[12]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[13]:
from setuptools.namespaces import flatten
list(flatten(source_list))
[13]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[14]:
numpy.sum(numpy.array(source_list, dtype=object))
[14]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]