【问题标题】:How to insert a list as a column in a 2D-list?如何在二维列表中插入列表作为列?
【发布时间】:2014-08-09 08:17:33
【问题描述】:

给定一个列表和一个二维列表(长度可能相同也可能不同)

list1 = [1,2,3,4]

list2 = [1,2]

table = [[1,2,0],
         [3,4,1],
         [4,4,4]]

我想将列表作为一列附加到二维列表中,充分管理空值。

result1 = [[1,2,0,         1],
           [3,4,1,         2],
           [4,4,4,         3],
           [None,None,None,4]]

result2 = [[1,2,0,   1],
           [3,4,1,   2],
           [4,4,4,None]]

这是我目前所拥有的:

table = [column + [list1[0]] for column in table]

但我在使用迭代器代替 0 时遇到语法问题。

我在想这样的事情:

table = [column + [list1[i]] for column in enumerate(table,i)]

但是我得到了一个连接到元组TypeError 的元组。我在想,旋转表格然后只追加一行并向后旋转可能是个好主意,但我无法正确处理大小问题。

【问题讨论】:

    标签: python arrays list multidimensional-array


    【解决方案1】:

    使用生成器函数和itertools.izip_longest

    from itertools import izip_longest
    
    def add_column(lst, col):
    
        #create the list col, append None's if the length is less than table's length
        col = col + [None] * (len(lst)- len(col))
    
        for x, y in izip_longest(lst, col):
            # here the if-condition will run only when items in col are greater than 
            # the length of table list, i.e prepend None's in this case.
            if x is None:
                yield [None] *(len(lst[0])) + [y] 
            else:
                yield x + [y]            
    
    
    print list(add_column(table, list1))
    #[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, 3], [None, None, None, 4]]
    print list(add_column(table, list2))
    #[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, None]]
    

    【讨论】:

      【解决方案2】:

      这个呢?

      table = [column + [list1[i] if i < len(list1) else None] for i, column in enumerate(list1)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-28
        • 2020-09-25
        • 1970-01-01
        • 2021-10-25
        • 2022-12-29
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        相关资源
        最近更新 更多