我做了一个按预期工作的小校验和程序。但是,当我取消注释只有print
语句的行时,结果会更改。也许是第8层错误,但这太奇怪了。
#!/usr/bin/env python3
string="foobarbaz" # Only as an example.
characters = string.encode('ISO-8859-1')
iterator = zip(characters[1:], characters)
iteratora = zip(characters[1::2], characters[::2])
iteratorb = zip(characters[2::2], characters[1::2])
# print(list(iterator))
# print(list(iteratora))
# print(list(iteratorb))
elements = [x + 2 * y if index % 2 else x * y
for index, (x, y) in enumerate(iterator)]
hex((sum(elements) + characters[0]) % 0x10000)
上面的代码按预期运行并返回以下内容:
'0xac66'
现在,我想取消注释第一个打印行,因此代码将如下所示:
#!/usr/bin/env python3
string="foobarbaz" # Only as an example.
characters = string.encode('ISO-8859-1')
iterator = zip(characters[1:], characters)
iteratora = zip(characters[1::2], characters[::2])
iteratorb = zip(characters[2::2], characters[1::2])
print(list(iterator))
# print(list(iteratora))
# print(list(iteratorb))
elements = [x + 2 * y if index % 2 else x * y
for index, (x, y) in enumerate(iterator)]
hex((sum(elements) + characters[0]) % 0x10000)
现在它返回:
'0x66'
list
语句中的print
转换是否会改变iterator
的原始值?我认为这不应该发生。
答案 0 :(得分:3)
list(iterator)
使用迭代器。因此,在取消注释print(list(iterator))
时,elements
将是一个空列表:
string = "foobarbaz"
characters = string.encode('ISO-8859-1')
iterator = zip(characters[1:], characters)
print(list(iterator))
# [(111, 102), (111, 111), (98, 111), (97, 98), (114, 97), (98, 114), (97, 98), (122, 97)]
elements = [x + 2 * y if index % 2 else x * y
for index, (x, y) in enumerate(iterator)]
print(elements)
# []
与:相比:
string = "foobarbaz"
characters = string.encode('ISO-8859-1')
iterator = zip(characters[1:], characters)
elements = [x + 2 * y if index % 2 else x * y
for index, (x, y) in enumerate(iterator)]
print(elements)
# [11322, 333, 10878, 293, 11058, 326, 9506, 316]
如果你想打印iterator
,你应该对其进行深度检查:
import copy
.
.
print(list(copy.deepcopy(iterator)))
.
.
另一种方法是在尝试打印之前将iterator
转换为列表:
.
.
iterator = list(zip(characters[1:], characters))
print(iterator)
# [(111, 102), (111, 111), (98, 111), (97, 98), (114, 97), (98, 114), (97, 98), (122, 97)]
elements = [x + 2 * y if index % 2 else x * y
for index, (x, y) in enumerate(iterator)]
print(elements)
# [11322, 333, 10878, 293, 11058, 326, 9506, 316]