2011-06-16 120 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'] 
相关问题