2016-03-03 58 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