[英]Python how to print attributes for itertools.permutations
I am new to Python and am trying out itertools
: 我是Python的新手,正在尝试itertools
:
import itertools as it
obj = it.permutations(range(4))
print(obj)
for perm in obj:
print( perm )
My Question: How do I view/print all the permutations in obj
directly without using a for
loop? 我的问题:如何在不使用for
循环的情况下直接查看/打印obj
所有排列?
What I Tried: I tried using __dict__
and vars
as suggested in this SO link but both do not work (former does not seem to exist for the object while latter generated 'TypeError: 'itertools.permutations' object is not callable'). 我尝试过的事情:我尝试按照此SO链接中的建议使用__dict__
和vars
,但两者都不起作用(该对象似乎不存在前者,而后者生成的'TypeError:'itertools.permutations'对象不可调用')。
Please pardon if my question is rather noobish - this attributes issue appears complicated and most of what is written in SO link flew over my head. 如果我的问题有点笨拙,请原谅-这个属性问题看起来很复杂,用SO链接编写的大部分内容都扑朔迷离。
Just cast your obj
to a list
: 只需将obj
转换为list
:
print(list(obj))
This will give you the following output: 这将为您提供以下输出:
[(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2), (0, 3, 2, 1), (1, 0, 2, 3), (1, 0, 3, 2), (1, 2, 0, 3), (1, 2, 3, 0), (1, 3, 0, 2), (1, 3, 2, 0), (2, 0, 1, 3), (2, 0, 3, 1), (2, 1, 0, 3), (2, 1, 3, 0), (2, 3, 0, 1), (2, 3, 1, 0), (3, 0, 1, 2), (3, 0, 2, 1), (3, 1, 0, 2), (3, 1, 2, 0), (3, 2, 0, 1), (3, 2, 1, 0)]
That's the direct answer to your question. 那是您问题的直接答案。 Another good thing to figure out is whether you really need what you are asking for. 要弄清楚的另一件好事是您是否真的需要您所要的东西。
You see, there is a reason why permutations
returns a generator . 您会看到, permutations
返回生成器是有原因的。 If you ain't familiar with that pattern, I'd strongly suggest reading about it. 如果您不熟悉这种模式,强烈建议您阅读一下。 To make a long story short, generally you don't wanna cast such things to a list
unless you really need it to be a list
(eg you want to access items directly by index). 长话短说,除非您确实需要将其作为list
(例如,您想直接通过索引访问项目),否则通常不需要将此类内容投射到list
。 In your case where you only need to print permutations there is absolutely nothing wrong with using for
loop. 在只需要打印排列的情况下,使用for
循环绝对没有错。
Here is one-liner to print one permutation per line: 这是一种单行打印每行一个排列的方法:
print('\n'.join(str(permutation) for permutation in obj))
But again, simple for
loop which you are using already is just fine. 但是同样,您已经在使用简单的for
循环就可以了。 Remember that simple is better than complex . 请记住, 简单胜于复杂 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.