如何将一个字符列表连接成8个字符串?

2024-04-26 10:32:35 发布

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

我有一个python字符列表,希望将它们连接起来创建一个字符串列表,每个字符串包含8个元素,例如:

x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']

结果

^{pr2}$

Tags: 字符串元素列表字符pr2
3条回答

可以使用join将字符数组转换为字符串。 以下是你在案件中的处理方法-

x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']
i = 0
strlist = []
while i<len(x):
  strlist.append(''.join(x[i:i+8]))
  i+=8

strlist将保存您分组的字符串。在

x = ['0','0','1','a','4','b','6','2','2','1','4','1','5','7','9','8']

简单地说:

^{pr2}$

^{} documentation包含一个grouper配方,该配方将连续项目分组为固定大小的组:

from itertools import *

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

现在,您只需分组到大小为8的列表中,然后将每个列表转换为一个字符串:

^{pr2}$

相关问题 更多 >