Python对象调用后无效
如果我对一个对象进行任何操作,它就会被取消。为什么会这样呢?看起来 list() 方法正在执行此操作。
from itertools import permutations
my_string = 'ada'
result = permutations(my_string)
result2 = permutations(my_string)
print(result)
print('Number of variations is: ', len(list(result)))
print(list(result))
print(' ')
print(result)
print('Number of variations is: ', len(list(result)))
print(list(result))
前三次尝试 print() 对象均成功。
<itertools.permutations object at 0x0000015B4B4555E0>
Number of variations is: 6
[('a', 'd', 'a'), ('a', 'a', 'd'), ('d', 'a', 'a'), ('d', 'a', 'a'), ('a', 'a', 'd'), ('a', 'd', 'a')]
第二次尝试 print() 它们给出 Null。
<itertools.permutations object at 0x0000015B4B4555E0>
Number of variations is: 0
[]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能多次迭代 itertools.permutations() 的结果。从您显示的结果来看,您似乎已经完成了:
迭代器只能使用一次。如果您需要第二次迭代排列,请再次调用
permuations()
,或者按住list(result)
。我注意到您打印了迭代器的值,并且两次都显示了完全相同的迭代器。
You cannot iterate multiple times through the result of itertools.permutations(). From the results you are showing, it looks like you have done:
An iterator can be used once and only once. If you need to iterate through the permutation a second time, either call
permuations()
again, or hold ontolist(result)
.I noticed that you printed the value of the iterator, and both times is showed the exact same iterator.
itertools.permutations
返回一个迭代器。迭代器只能循环一次。在执行
list(result)
后,result
迭代器已耗尽,因此len(result)
将为 0。我还假设您做了一个复制输出时出错,因为当您实际运行代码时,只有第一个调用(
len(list(result))
)给出预期输出。itertools.permutations
returns an iterator. Iterators can only be looped over once.After you do
list(result)
, theresult
iterator is exhausted and thuslen(result)
will be 0.I also assume you made a mistake while copying the output since when you actually run the code, only the first call(
len(list(result))
) gives the expected output.