压平列表

碾平列表是个很好玩的函数。好比你有个嗷嗷恶心的列表:html

[[1, 2], [3, [4], [5, 6], 7], 8]

你想把它变成正常一点的python

[1, 2, 3, 4, 5, 6, 7, 8]

要怎么办呢?linux

 

老实说,好久不接触这种东西,我已经早忘了当初是怎么写的了,憋了半天没写出来,后来参考了 http://www.cnblogs.com/c-hy/archive/2012/09/21/2696703.html 才回忆起来。windows

而后,着重介绍三种方法:app

 

一、使用sum和map,感受玩的比较炫,你们来感觉一下:函数

from collections import Iterable


def flatten(x):
    if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
        return sum(map(flatten, x), [])
    else:
        return [x]


lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(flatten(lst))

刚才那个网页中说,国外某论坛的大神写了一个匿名函数spa

flat=lambda L: sum(map(flat,L),[]) if isinstance(L,list) else [L]

基本上是一个意思的。code

 

二、使用yield。这个是在《Python Cookbook》中介绍的一种方法htm

from collections import Iterable


def flatten(items, ignore_types=(str, bytes)):
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, ignore_types):
            yield from flatten(x)
        else:
            yield x


items = [[1, 2], [3, [4], [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
    print(x)

yield from 比较巧妙。不过,这里有个限制,yield from是python3才有的,若是是在python2中使用,须要这么写:blog

from collections import Iterable


def flatten(items, ignore_types=(str, bytes)):
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, ignore_types):
            for i in flatten(x):
                yield i
        else:
            yield x


items = [[1, 2], [3, [4], [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
    print(x)

2和3通用。不得不说yield真是个好东西。

 

三、Tkinter自带函数_flatten。不说话,直接上代码

from Tkinter import _flatten
lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(_flatten(lst))

这个就比较可怕了。不过Tkinter这东西,听说只有windows才有,linux没有。mac不太清楚。

 

固然,其余方法也是有的,好比

def flatten(x):
    for i in x:
        if isinstance(i, Iterable) and not isinstance(i, (str, bytes)):
            flatten(i)
        else:
            new_lst.append(i)


new_lst = []
lst = [1, 2, [3, [4], [5, 6], 7], 8]
flatten(lst)
print(new_lst)

(感谢群友提供)思路比较简单,代码也很清晰,只是全局列表到底仍是感受有一点点耍赖。

固然,要说耍赖,这里还有更耍赖的,好比

lst = [1, 2, [3, [4], [5, 6], 7], 8]
print(list("[" + str(lst).replace("[", "").replace("]", "") + "]"))

还有

import re
lst = [1, 2, [3, [4], [5, 6], 7], 8]
print map(int, re.findall('\d+', str(lst)))

哈哈,很特定的环境下可使用,好比第一个列表元素中不能含有"["和"]",第二个更是只能包含整数。不过,同窗们的脑洞仍是比较大的。

记录一下,留着玩。

相关文章
相关标签/搜索