我有一个字符串列表,如下所示:
sixbit = ['000011', '000001', '010100', '100001']
我想遍历这个列表并生成一个如下所示的新列表:
eightbit = ['00001100', '00010101', '00100001']
出于说明的目的,len(sixbit) 等于 4,因为它可以很好地转换为八位。理想情况下,六位可以是任意长度——如果八位“切断”任何剩余的 1 或 0 就可以了。
这是我尝试过的一些代码...遗憾的是,它偏离但也许您可以看到我正在尝试做什么。这个想法是 1) 将所有数字放入一个大字符串中 2) 遍历每个数字并继续计数,在迭代时将数字收集到 holder 3) 当 count = 8 附加到列表时 4) 继续迭代
def compress_six_bit(ary):
final_list = []
holder = ''
temp_string = ''
encode_counter = 0
for i in ary:
holder = holder + i
while encode_counter < 8:
encode_counter = encode_counter + 1
temp_string = temp_string + i
final_list.append(temp_string)
encode_counter = 0
temp_string = ''
return final_list
最佳答案
>>> chained = itertools.chain.from_iterable(sixbit)
>>> [''.join(bits) for bits in itertools.izip(*[chained]*8)]
['00001100', '00010101', '00100001']
解释
chained
只是原始字符串所有字母的迭代器。它使用 chained
来自 itertools
的函数。
>>> chained = itertools.chain.from_iterable(sixbit)
>>> list(chained)
['0', '0', '0', '0', '1', '1', '0', '0', '0', '0', '0', '1', '0', '1', '0', '1', '0', '0', '1', '0', '0', '0', '0', '1']
[chained]*8
创建包含 相同 chained
对象 8 次的列表。
*
只是将这 8 个元素解压到 izip
中参数。
izip
只返回元组,第一个包含参数中每个链式迭代器的第一个字母,第二个元组包含第二个字母,等等。有 8 个链式对象,因此每个元组中有 8 个字母。
最重要的是,字母取自每个迭代器,但实际上是同一个迭代器的 8 个实例。每次调用都会消耗它。所以第一个元组包含链式迭代器的前 8 个字母。
>>> chained = itertools.chain.from_iterable(sixbit)
>>> list(itertools.izip(*[chained]*8))
[('0', '0', '0', '0', '1', '1', '0', '0'), ('0', '0', '0', '1', '0', '1', '0', '1'), ('0', '0', '1', '0', '0', '0', '0', '1')]
在最后一步,我们加入他们的列表理解:
>>> chained = itertools.chain.from_iterable(sixbit)
>>> [''.join(bits) for bits in itertools.izip(*[chained]*8)]
['00001100', '00010101', '00100001']
关于python - 遍历字符串列表并组合字符串值 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418751/