【问题标题】:Create a 2D list that appends value as a column when repeating assign the index创建一个二维列表,在重复分配索引时将值作为列附加
【发布时间】:2021-03-23 15:52:10
【问题描述】:

给定一个列表标签

Label=np.empty((2,1), dtype=object) # array([[None], [None]], dtype=object)
#first row should be like this;
Label[0][0] = [Label[0][0], 1] # output array([[list([1])], [None]], dtype=object)
Label[0][0] = [Label[0][0], 3] # output array([[list([1,3])], [None]], dtype=object)

#the second row
Label[1][0] = [Label[1][0], 2] # output array([[list([1,3])], [list([2])]], dtype=object)
Label[1][0] = [Label[1][0], 4] # output array([[list([1,3])],[list([2,4])]], dtype=object)

我尝试了以下方法。

#1. 
Label[0][0] = [a + b for (a, b) in zip([Label[0][0]], [1])]
#I got an error -> TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'


#2.
Label[0][0] = [Label[0][0],1] #It gives a list with a different structure

非常感谢您的帮助。

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    我创建了这个功能,暂时对我有帮助

    import numpy as np
    def add(lst,col):
      if lst == [None] or not last:
          return [col]
      elif len(lst) == 1:
          return [lst[0],col]
      else:        
          n = len(lst)-1
          return np.insert(lst, n, col)
    

    这就是我测试它的方式

    Label=np.empty((2,1), dtype=object)
    Label[0][0] = list(add(Label[0][0],1)) #[array([[list([1])],[None]],dtype=object)
    Label[0][0] = list(add(Label[0][0],2)) #[array([[list([1,2])],[None]],dtype=object)
    Label[0][0] = list(add(Label[0][0],3)) #[array([[list([1,2,3])],[None]],dtype=object)
    
    Label[1][0] = list(add(Label[1][0],4)) #[array([[list([1,2,3])],[list([4])]],dtype=object)
    Label[1][0] = list(add(Label[1][0],5)) #[array([[list([1,2,3])],[list([4,5])]],dtype=object)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2011-12-06
      • 2016-05-10
      相关资源
      最近更新 更多