如何向迭代器项添加前缀?

2024-06-26 02:38:52 发布

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

所以我试图把一个二进制字符串转换成一个字符,但是每个字符串都存储在一个迭代器中,所以我不能在它们前面添加一个b。如何更改代码以实现此目的?你知道吗

originalText = "This is a message!"
text2Binary = [format(ord(x), 'b') for x in originalText]

textLength = len(originalText)
text2BinaryList = iter(text2Binary)
binary2TextCycler = next(text2BinaryList)

for i in range(textLength):
    print(binary2TextCycler)

Tags: 字符串代码in目的messageforis二进制
2条回答

我认为您的主要问题是您缺少迭代的工作方式。你知道吗

originalText = "This is a message!"
text2Binary = [format(ord(x), 'b') for x in originalText]

现在您有了一个列表,它已经是表示每个字符的二进制字符串的一个iterable。我想这就是你想要的。您只需迭代它们即可将其打印出来:

for binary in text2Binary:
    print(binary)

如果您想更改它们的打印格式,只需更改传递给原始理解中format的格式字符串:

text2Binary = [format(ord(x), '#010b') for x in originalText]

#表示“备用格式”,0表示用0填充,10表示填充到10个字符,因此得到的结果是:

0b01010100
0b01101000
0b01101001
0b01110011
… etc.

如果您需要不同的格式,只需使用不同的格式规范即可。要添加额外的字符,您可能需要使用str.format,而不是只使用format

text2Binary = ['b{:b}'.format(ord(x)) for x in originalText]

…或f字串:

text2Binary = [f'b{ord(x):b}' for x in originalText]

现在,让我们看看您添加的所有额外内容:

textLength = len(originalText)
# ...
for i in range(textLength):

虽然这个可以工作,但是你不需要某个东西的长度来迭代它;只需要直接迭代它。你知道吗

同时:

text2BinaryList = iter(text2Binary)
binary2TextCycler = next(text2BinaryList)

这将在列表上创建一个迭代器,然后从该迭代器中获取第一个元素。所以,binary2TextCycler就是字符串'0b01010100'。不管您在其他iterable上循环多少次,比如range(textLength),每次都会得到相同的第一个字符串。你知道吗

作为旁注:text2Binary是一个列表,text2BinaryList是该列表上的迭代器。这是相当混乱的命名,这可能是为什么你困惑自己。你知道吗

无论如何,如果您想让它工作,您必须再次推进迭代器并在每次循环中存储新值:

for i in range(textLength):
    print(binary2TextCycler)
    binary2TextCycler = next(text2BinaryList)

但如果您了解for循环是如何工作的,那么这相当于:

text2BinaryList = iter(text2Binary)
binary2TextCycler = next(text2BinaryList)
textLengthIterator = iter(range(textLength))
while True:
    try:
        i = next(textLengthIterator)
    except StopIteration:
        break
    print(binary2TextCycler)
    binary2TextCycler = next(text2BinaryList)

显然,您可以删除额外的next

text2BinaryList = iter(text2Binary)
textLengthIterator = iter(range(textLength))
while True:
    try:
        i = next(textLengthIterator)
        binary2TextCycler = next(text2BinaryList)
    except StopIteration:
        break
    print(binary2TextCycler)

因此,很明显,您可以通过在两个iterable中的zip上循环来替换它:

for i, binary2TextCycler in zip(range(textLength), text2BinaryList):
    print(binary2TextCycler)

然后,您不需要iter;您可以直接使用iterable:

for i, binary2TextCycler in zip(range(textLength), text2Binary):
    print(binary2TextCycler)

而且,由于实际上没有对任何东西使用i,而且两个iterable的长度相同,因此可以完全删除第一个:

for binary2TextCycler in text2BinaryList:
    print(binary2TextCycler)

像这样?你知道吗

originalText = "This is a message!"
text2Binary = [format(ord(x), 'b') for x in originalText]

textLength = len(originalText)
text2BinaryList = iter(text2Binary)
binary2TextCycler = next(text2BinaryList)

for i in range(textLength):
    print('b%s' %(binary2TextCycler))

退货

b1010100
b1010100
b1010100
b1010100
b1010100
b1010100
b1010100
b1010100...

相关问题 更多 >