簡體   English   中英

在與最長列表長度相同的列表列表中創建一個新列表

[英]Create a new list in a list of lists that has the same length as the longest one

如果我有以下列表:

data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7]]

有沒有辦法在第二個和第三個(最好在任何位置)之間創建一個與此列表中最長的列表長度相同的列表?

例如,在我的例子中,在第二個和第三個/最后一個列表之間創建一個與最后一個長度相同的列表(因為這是長度為 7 的最長列表):

data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7]]

我在帶有熊貓的數據框中使用這些數據。 也許熊貓可以幫助我實現我的目標?

首先獲取最長的子列表,然后創建該長度的新列表(通過復制它或您需要的任何內容)。 然后將新列表插入到您所需位置的data中。

data = [[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7]]

longest_sublist = max(data, key=len)
new_list = longest_sublist.copy()

desired_position = 2
data.insert(desired_position, new_list)

之后, data變為:

[[1, 2, 3], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]]

由於沒有提供新列表的特定元素,您可以簡單地復制最長的子列表,然后insertinsertdata

data = sorted(data, key=len) # for when lists are not organized by len

new = ['x']*len(data[-1])
data.insert(-1, new)
# [[1, 2, 3], [1, 2, 3, 4, 5], ['x', 'x', 'x', 'x', 'x', 'x', 'x'], [1, 2, 3, 4, 5, 6, 7]]

其實很簡單

def insert_sublist(list_of_lists, position):
    ideal_sized_list = list(range(max([len(i) for i in list_of_lists])))
    return list_of_lists[:position]+[ideal_sized_list]+list_of_lists[position:]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM