簡體   English   中英

根據Python中的計數器值將列表分為多個子列表

[英]Split list in to multiple sublists based on counter value in Python

我似乎找不到答案,但是我想根據一個計數器將一個列表分成多個較小的列表,以便新列表每次都包含相同的最大數量的值。

創建新的子列表后,我想繼續逐步瀏覽原始列表,以基於下一個值創建新的子列表。

keywordList = ["24/7 home emergency", "6 month home insurance", "access cover", "access insurance",
              "are gas leaks covered by home insurance", "central heating breakdown cover", "trace & access",
              "trace and access", "trace and access costs"]
maxLength = 4

for c, items in enumerate(keywordList):
    if c < maxLength:
        #append items to new list here

預期的輸出將是三個新列表,前兩個長度為四個元素,最后一個長度為一個元素。 但是,如果原始列表突然有100個元素,我們將獲得25個新列表。

似乎有關於均勻分割原始列表的信息,但是沒有關於預定值的信息。 任何幫助表示贊賞,謝謝。

編輯以反映您當前的問題:

keywordList = ["24/7 home emergency", "6 month home insurance", "access cover", "access insurance",
              "are gas leaks covered by home insurance", "central heating breakdown cover", "trace & access",
              "trace and access", "trace and access costs"]

leng = len(keywordList)
keywordList += [""] * ((leng//4+1)*4 - leng)
result = [[keywordList[i] for i in range(j, j+4)] for j in range(0, leng, 4)]
result[-1] = [e for e in result[-1] if e]

result

[['24/7 home emergency',
  '6 month home insurance',
  'access cover',
  'access insurance'],
 ['are gas leaks covered by home insurance',
  'central heating breakdown cover',
  'trace & access',
  'trace and access'],
 ['trace and access costs']]

此方法的想法是將空列表(可以是任何東西)的keywordList為4的倍數,然后除以4。之后,清除空字符串的最后一個元素(或我們決定表示空對象的任何內容)

如果您想吐出您的清單到多個子清單,您可以使用以下清單理解:

from itertools import repeat, zip_longest

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

iter_l = iter(l)

[list(filter(None.__ne__, i)) for i in zip_longest(*repeat(iter_l, 4))]
# [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

暫無
暫無

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

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