如何将列表或字符串解析为固定长度的块

2024-04-19 10:07:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的被一个基本的问题困住了。我试着把一个项目列表分成一个包含许多项目的列表,每个项目的字符长度为10。例如,给出一个包含一个项的列表,['111111111122222222223333333333'],输出将产生:

1111111111
2222222222
3333333333

我觉得这太简单了,但我被难住了。我试图创建这样的函数:

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

显然,这不起作用。有什么建议吗?使用字符串会比使用列表更容易吗?


Tags: 项目函数inparser列表forlenreturn
3条回答

虽然这个问题已经发布了4年,但是这里有一个另一种方法来使用^{} module。从文档中:

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

Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

Optional keyword arguments correspond to the instance attributes of TextWrapper, documented below. width defaults to 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
>>> 

使用:

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

有人问了一个相关的问题: 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']

相关问题 更多 >