2016-03-03 56 views
0

我想将关键字无附加到列表中。将附加关键字无添加到列表中的子列表

  1. 如果输入列表 中的元素数小于rows *列,则使用关键字None填充二维列表。
  2. 如果输入列表中的元素数大于行*列 ,则忽略多余的元素。

对于给定的try_convert_1D_to_2D([1, 2, 3, 4], 3, 4)输入我想实现这样的事情:[[1, 2, 3, 4], [None, None, None, None], [None, None, None, None]]

我想的是:

def try_convert_1D_to_2D(my_list, r, c): 
    a=r*c 
    b=len(my_list) 
    if(b >= a): 
     l=[my_list[i:i+c] for i in range(0,b,c)] 
     return l[0:r] 
    else: 
     for i in range(0,b,c): 
      k=my_list[i:i+c] 
      return [k.append(None) for k in a] 

对于输入

try_convert_1D_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3) 

我能做到[[8, 2, 9],[4, 1, 6]]这是正确的。

有人请指教我在哪里做错了,请建议我如何才能做到最好。谢谢。

+0

请提供你得到不符合预期的结果。 – ShadowRanger

+0

为了记录,在listcomp中使用'k.append(None)'几乎肯定会导致问题; 'list.append'不返回'list',它只是返回'None',所以listcomp只是返回一个'list',等价于你得到的'[无] * len(a) '。 listcomp也覆盖/忽略你刚才定义的'k'。 – ShadowRanger

回答

1

我指出several issues in the comments,这里是实际工作的版本:

def try_convert_1D_to_2D(my_list, r, c): 
    # Pad with Nones to necessary length 
    padded = my_list + [None] * max(0, (r * c - len(my_list))) 
    # Slice out rows at a time in a listcomp until we have what we need 
    return [padded[i:i+c] for i in range(0, r*c, c)] 
+0

非常感谢您的回答,并纠正了代码中的错误。 – rocky25bee