Python – 將一維列表轉換為長度可變的二維列表


Python中的列表通常是一維列表,元素一個接一個地排列。但在二維列表中,我們有巢狀在外層列表中的列表。在本文中,我們將學習如何從給定的一個維列表建立一個二維列表。我們還向程式提供二維列表中元素數量的值。

使用append和索引

在這種方法中,我們將建立一個for迴圈來遍歷二維列表中的每個元素,並將其用作要建立的新列表的索引。我們透過從零開始遞增索引值並將其新增到從二維列表中接收到的元素來保持索引值的遞增。

示例

# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 2, 4]

#Declare empty new list
res = []
def convert(listA, len_2d):
   idx = 0
   for var_len in len_2d:
      res.append(listA[idx: idx + var_len])
      idx += var_len
convert(listA, len_2d)
print("The new 2D lis is: \n",res)

執行上述程式碼,我們得到以下結果:

輸出

The new 2D lis is:
[[1, 2], [3, 4, 5, 6]]

使用islice

islice函式可用於根據二維列表的要求切片給定列表中的某些元素。因此,在這裡我們遍歷二維列表的每個元素,並使用該值2來切片原始列表。我們需要itertools包來使用islice函式。

示例

from itertools import islice
# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 3, 2]

# Use islice
def convert(listA, len_2d):
   res = iter(listA)
   return [list(islice(res,i)) for i in len_2d]
res = [convert(listA, len_2d)]
print("The new 2D lis is: \n",res)

執行上述程式碼,我們得到以下結果:

輸出

The new 2D lis is:
[[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu']]]

更新於:2020年12月28日

2K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.