Python 印刷组合问题
itertools函数没有错误,但一旦完成,它也不会打印任何内容。 我的代码是:Python 印刷组合问题,python,combinations,Python,Combinations,itertools函数没有错误,但一旦完成,它也不会打印任何内容。 我的代码是: def comb(iterable, r): pool = tuple(iterable) n = len(pool) for indices in permutations(range(n), r): if sorted(indices) == list(indices): print (indices) yield tupl
def comb(iterable, r):
pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
if sorted(indices) == list(indices):
print (indices)
yield tuple(pool[i] for i in indices)
我包含了print语句,但它不打印它计算的总组合。它返回一个对象。如果您反复浏览它,您将看到打印。例如:
for x in comb(range(3),2):
print "Printing here:", x
给你:
(0, 1) # due to print statement inside your function
Printing here: (0, 1)
(0, 2) # due to print statement inside your function
Printing here: (0, 2)
(1, 2) # due to print statement inside your function
Printing here: (1, 2)
因此,如果您只想逐行打印组合,请删除函数中的print语句,并将其转换为列表或对其进行迭代。您可以按以下方式逐行打印这些内容:
print "\n".join(map(str,comb(range(4),3)))
给你
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
你需要仔细阅读发电机的工作原理。调用
comb()
时,它返回一个生成器对象。然后,您需要对生成器对象执行一些操作,以获取从中返回的对象
from itertools import permutations
lst = range(4)
result = list(comb(lst, 2)) # output of print statement is now shown
print(result) # prints: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
comb()
返回生成器对象。然后,list()。在迭代时,您的print语句将激发。我得到以下错误:对于排列中的索引(范围(n),r):NameError:未定义全局名称“排列”。您需要有一个导入
语句。我在我的示例中添加了一个。为什么要创建一个整数列表,只要输入数据,生成它们的排列,将每个排列作为原始数据的一对索引使用,并生成结果?哦,因为你想过滤它们来订购?这就是itertools.compositions
的用途;它直接替代了您的整个功能。