在 Python 中查詢巢狀列表中的最大長度子列表


在 Python 中進行資料分析時,我們經常會處理巢狀列表。在本文中,我們將瞭解如何找出巢狀列表中元素中最長的列表,然後列印該列表及其長度。

使用 lambda 和 map

我們宣告一個巢狀列表,並將其作為輸入傳遞給 lambda 函式以及其長度。最後,我們應用 max 函式來獲取長度最大的列表以及此類列表的長度。

示例

 線上演示

def longest(lst):
   longestList = max(lst, key = lambda i: len(i))
   maxLength = max(map(len, listA))
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,65,2]]
print("Longest List and its length:\n",longest(listA))

輸出

執行上述程式碼將得到以下結果:

Longest List and its length:
([2, 45, 6, 7], 4)

使用 len 和 max

在這種方法中,我們首先找到長度最大的子列表,然後遍歷列表的元素以找出哪些子列表與該長度匹配。我們使用 max 和 len 函式來進行此計算。

示例

 線上演示

def longest(lst):
   longestList = []
   maxLength = max(len(x) for x in listA)
   for i in listA:
      if len(i) == maxLength :
         longestList = i
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,6,2]]
print("Longest List and its length:\n",longest(listA))

輸出

執行上述程式碼將得到以下結果:

Longest List and its length:
([2, 45, 6, 7], 4)

使用 map

這與上述程式類似,但我們使用 map 函式來找出長度最大的子列表。

示例

 線上演示

def longest(lst):
   longestList = []
   maxLength = max(map(len,listA))
   for i in listA:
      if len(i) == maxLength :
         longestList = i
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,6,2]]
print("Longest List and its length:\n",longest(listA))

輸出

執行上述程式碼將得到以下結果:

Longest List and its length:
([2, 45, 6, 7], 4)

更新於: 2021年1月25日

823 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.