zoukankan      html  css  js  c++  java
  • 如何将list嵌套的list的[]去掉

    比如说

    a = [[1,2,3], [5, 2, 8], [7,8,9]]

    我们需要将里面的[]去掉,但是又不删除任意元素

    如果list里里面的元素是数字,‘1’也是可以的,那么我们可以使用np.ravel

    a = [[1,2,3], [5, 2, 8], [7,8,9]]
    
    list(np.ravel(a))
    #[1, 2, 3, 5, 2, 8, 7, 8, 9]

    或者

    a = [['1',2,3], [5, 2, 8], [7,8,9]]
    
    list(np.ravel(a))
    #['1', '2', '3', '5', '2', '8', '7', '8', '9']

    但是下面这种就不可以

    a = [[1,2,3],1, [5, 2, 8], [7,8,9]]
    
    list(np.ravel(a))
    #[[1, 2, 3], 1, [5, 2, 8], [7, 8, 9]]

    使用起来比较严格

    反正都是要求元素是list或者是str,但是不能是int

    from itertools import chain
    a = [['1','2','3'],'1']
    list(chain(*a))
    #['1', '2', '3', '1']  或者是list(chain.from_iterable(a)

    实在不行就写个循环语句

    func = lambda x: [y for l in x for y in func(l)] if type(x) is list else [x]
    func(a)

     自定义一个函数

    def flat(a):
        l= []
        for i in a:
            if type(i) is list:
                for j in i:
                    l.append(j)
            else:
                l.append(i)
        return(l)
    
    flat(a)
  • 相关阅读:
    sss
    stm32cube使用
    FreeRTOS
    嵌入式网站
    CRC分段校验
    IAR编译器
    (转)UCOSII源代码剖析
    (转)stm32硬件IIC
    keil MDK注意事项
    (转).Net中自定义类作为Dictionary的key详解
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/14063676.html
Copyright © 2011-2022 走看看