Skip to main content
 首页 » 编程设计

Python 如何打印 itertools.permutations 的属性

2025年05月04日24落叶无声

我是 Python 的新手,正在试用 itertools :

import itertools as it 
obj = it.permutations(range(4)) 
print(obj) 
for perm in obj: 
    print( perm ) 

我的问题:如何查看/打印 obj 中的所有排列直接而不使用 for循环?

我的尝试: 我尝试使用 __dict__和 vars正如本 SO link 中所建议的但两者都不起作用(对象似乎不存在前者,而后者生成“类型错误:‘itertools.permutations’对象不可调用”)。

请原谅我的问题有点菜鸟 - 这个属性问题看起来很复杂,大部分内容都写在 SO link 中飞过我的头顶。

请您参考如下方法:

只需将您的 obj 转换为 list:

print(list(obj)) 

这将为您提供以下输出:

[(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)] 

这是对您问题的直接回答。弄清楚的另一件好事是您是否真的需要您所要求的。

你看,permutations 是有原因的返回 generator .如果您不熟悉该模式,我强烈建议您阅读它。长话短说,通常你不想将这些东西转换到 list 除非你真的需要它是一个 list (例如你想直接访问项目按索引)。在您只需要打印排列的情况下,使用 for 循环绝对没有错。

这是一行,每行打印一个排列:

print('\n'.join(str(permutation) for permutation in obj)) 

但同样,您已经在使用的简单 for 循环就可以了。请记住 simple is better than complex .