2

python列表展开

 2 years ago
source link: https://www.hi-roy.com/posts/python%E5%88%97%E8%A1%A8%E5%B1%95%E5%BC%80/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python列表展开

2014-04-09

某网站今年笔试题,本质就是把某多维数组变成一维数组并去重。本来要求用JS实现,不过用python更简洁一点,就是对列表进行展开操作,递归就KO了。

首先来个不简洁的:

arr = [1, [1, 2, [2, 3]], [4], [4]]
final=[]
def change(x):
    print "x is:",x
    if isinstance(x, list):
        for l in x:
            print "l is:",l
            change(l)
    else:
        final.append(x)
        print "now final is",final
change(arr)
print final
change = lambda x: [y for l in x for y in change(l)] if type(x) is list else [x]
print change(arr)

至于去重就使用set()就可以了。

Roy avatar
About Roy
野生程序猿,略懂Python,略懂Golang,略懂云计算,略懂大数据,略懂拳击游泳钓鱼,略懂钢琴吉他摄影。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK