首页 > 编程语言 > 详细

python 笔试题 嵌套列表剥离

时间:2021-03-30 22:12:57      阅读:29      评论:0      收藏:0      [点我收藏+]

 

list1 = [11, [22, 3], [4, ], [55, 66], 8, [9, [7, [12, [34, [26]]]]]]
# 去除多余嵌套的列表,得到[11, 22, 3, 4, 55, 66, 8]

# 小剥皮
# [11, [22, 3]]
# [11, [22, [3, 4]]
def func(x):
    return [a for b in x for a in func(b)] if isinstance(x, list) else [x]

def f(x):
    ret = []
    for b in x:
        if isinstance(b, list):
            for a in f(b):
                ret.append(a)
        else:
            ret.append(b)
    return ret

list2 = [11, 22, [33, 44], [55, [66, 77]], [88, [99, [100, [200, [300]]]]]]
ret = f(list2)
print(ret)
ret2 = func(list2)
print(ret2)

 

str_list = str(list1)
str_list = str_list.replace([, ‘‘)
str_list = str_list.replace(], ‘‘)
ret = [int(i) for i in str_list.split(, )]
print(ret)

 

python 笔试题 嵌套列表剥离

原文:https://www.cnblogs.com/happyfan/p/14598714.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!