2011-06-16 122 views
6

我真的被困在一個基本問題上。我試圖把一個列表中的一個項目,並把它分成很多項目的列表中的每個具有10系統字符長度例如給予單個項目的列表,['111111111122222222223333333333'],輸出會產生:如何解析一個列表或字符串爲固定長度的塊

1111111111 
2222222222 
3333333333 

我覺得這很簡單,但我很難過。我試圖創建一個這樣的功能:

def parser(nub):  
    while len(nub) > 10: 
     for subnub in nub: 
      subnub = nub[::10] 
      return(subnub) 
    else: 
     print('Done') 

很明顯,這是行不通的。有什麼建議?使用字符串比列表更容易嗎?

+0

你能改說這個嗎:'我試圖通過一個n長度的列表迭代到10個字符的子列表中。'我不明白。 – mouad 2011-06-16 13:06:54

+0

@mouad編輯爲清晰,我希望有幫助。 – drbunsen 2011-06-16 13:25:51

+0

編輯拼寫標題。此外,你的字符串不需要在列表中。另外,我還沒有回答你的問題嗎? (見下文) – 2011-06-16 13:33:03

回答

9

一個相關的問題已經被問: Slicing a list into a list of sub-lists

例如,如果你的源列表是:

the_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... ] 

,你可以把它分解喜歡:

split_list = [the_list[i:i+n] for i in range(0, len(the_list), n)] 

假設n是你的子列表長度和結果將是:

[[1, 2, 3, ..., n], [n+1, n+2, n+3, ..., 2n], ...] 

然後你可以遍歷它想:

for sub_list in split_list: 
    # Do something to the sub_list 

同樣的事情也適用於字符串。

這裏有一個實際的例子:

>>> n = 2 
>>> listo = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> split_list = [listo[i:i+n] for i in range(0, len(listo), n)] 
>>> split_list 
[[1, 2], [3, 4], [5, 6], [7, 8], [9]] 

>>> listo = '123456789' 
>>> split_list = [listo[i:i+n] for i in range(0, len(listo), n)] 
>>> split_list 
['12', '34', '56', '78', '9'] 
+0

謝謝,那正是我所需要的。非常感謝您的幫助! – drbunsen 2011-06-16 13:48:29

1

用途:

value = '111111111122222222223333333333' 
n = 10 
(value[i:i+n] for i in xrange(0, len(value), n)) 
1

儘管這個問題已經經過4年的過帳,但這裏是另一種方式來做到這一點使用textwrap module。從文檔:

textwrap.wrap(text[, width[, ...]])

裹在文本的一個段落(字符串),所以每行至多寬度字符。返回輸出行的列表,沒有最終的換行符。

可選的關鍵字參數對應於TextWrapper的實例屬性,如下所述。寬度默認爲70。

因此,我們可以做這樣的:

>>> import textwrap 
>>> myList = ['111111111122222222223333333333'] 

>>> [i for text in myList for i in textwrap.wrap(text, 10)] 
['1111111111', '2222222222', '3333333333'] 

>>> for i in [i for text in myList for i in textwrap.wrap(text, 10)]: 
...  print i 
1111111111 
2222222222 
3333333333 
>>> 
0

其他方式遞歸做到這一點:

選項1:遞歸函數

>>> def chunks(x, n=10): 
...  if len(x) <= n: 
...   return [x] 
...  else: 
...   return [x[:n]] + chunks(x.replace(x[:n], '')) 
... 
>>> seq = ['111111111122222222223333333333'] 
>>> print chunks(seq[0]) 
['1111111111', '2222222222', '3333333333'] 

選項2:遞歸lambda

>>> n = 10 
>>> chunks = lambda x: [x] if len(x) <= n else [x[:n]] + chunks(x.replace(x[:n], '')) 
>>> print chunks(seq[0]) 
['1111111111', '2222222222', '3333333333'] 
相關問題