Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/visual-studio-2010/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的字符串分组_Python_Python 3.x_Loops_For Loop_Grouping - Fatal编程技术网

Python中的字符串分组

Python中的字符串分组,python,python-3.x,loops,for-loop,grouping,Python,Python 3.x,Loops,For Loop,Grouping,我正在工作 如果字符串是'1111122223333344444',并且我想要5个组,那么如何对这些对进行分组和比较 例如,我想对“11111”和“22222”、“33333”和“44444”进行分组和比较。这怎么可能呢 我使用了这个代码,在4之后不断得到额外的行 >>> for i in range(0, int(len(string)/size)): ... print(string[previous : previous + size]) ... prin

我正在工作

如果字符串是'1111122223333344444',并且我想要5个组,那么如何对这些对进行分组和比较

例如,我想对“11111”和“22222”、“33333”和“44444”进行分组和比较。这怎么可能呢

我使用了这个代码,在4之后不断得到额外的行

>>> for i in range(0, int(len(string)/size)):
...     print(string[previous : previous + size])
...     print(string[previous + size : previous + size * 2])
...     previous += size * 2

11111
22222
33333
44444

还有其他方法吗?

您可以使用
zip
习惯用法将元素分组为已知大小的组

s='11111222223333344444'
for i in zip(*[iter(s)]*5):
    print(i)
产出:

('1', '1', '1', '1', '1')
('2', '2', '2', '2', '2')
('3', '3', '3', '3', '3')
('4', '4', '4', '4', '4')
11111
22222
33333
44444
如果您想将它们作为单个字符串,可以使用
'.join

for i in zip(*[iter(s)]*5):
    print(''.join(i))
产出:

('1', '1', '1', '1', '1')
('2', '2', '2', '2', '2')
('3', '3', '3', '3', '3')
('4', '4', '4', '4', '4')
11111
22222
33333
44444

有几种方法可以做到这一点。经典的实现是通过列表理解:

chunks = [string[i:i + 5] for i in range(0, len(string), 5)]
使用itertools.zip_是我的首选:

def chunk(seq, size):
    for ch in itertools.zip_longest(*([iter(seq)] * size)):
        if None in ch:
            ch = ch[:ch.index(None)]
        yield ''.join(ch)
def grouper(i,组大小):
开始=0
结束=组大小
启动时
比较?什么意思?他们是不同的。你的意思是你可以有10次
1
?一般来说,比较一下,但特别是这个项目,我需要取字符串的平均汉明距离。所以我需要计算第一个和第二个字符串、第三个和第四个字符串的汉明距离,然后计算平均值。这里有很多无关的副本
,而len(I[start:]):yield seq[start:start+group_size];start+=group_size
无需跟踪单独的
end
变量。如何使用已解码的base 64字符串进行跟踪。例如,
base64.b64解码(字符串)
@PatrickHaugh