我真的卡在一个基本问题上了。我正在尝试获取一个项目的列表并将其分成许多项目的列表,每个项目的字符长度为 10。例如,给出一个包含一个项目的列表,['11111111112222222222233333333333']
,输出将产生:
1111111111
2222222222
3333333333
我觉得这非常简单,但我很难过。我试图创建一个这样的函数:
def parser(nub):
while len(nub) > 10:
for subnub in nub:
subnub = nub[::10]
return(subnub)
else:
print('Done')
显然,这是行不通的。有什么建议吗?使用字符串会比使用列表更容易吗?
最佳答案
有人问了一个相关的问题: 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']
关于python - 如何将列表或字符串解析为固定长度的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6372228/