【发布时间】:2016-05-01 22:48:04
【问题描述】:
我是生成器的新手。为什么当我将 print 替换为 yield (Python 2.7)
时,带有 print 语句的第一个正确函数不起作用首先使用 print 的正确函数:
def make_all_pairs(list_):
pivot = list_.pop(0)
for el in list_:
pair = (pivot, el)
print pair
if len(list_) > 1:
make_all_pairs(list_)
make_all_pairs(["a","b","c","d","e"])
('a', 'b')
('a', 'c')
('a', 'd')
('a', 'e')
('b', 'c')
('b', 'd')
('b', 'e')
('c', 'd')
('c', 'e')
('d', 'e')
然后是没有给出所有组合的生成器
def make_all_pairs(list_):
pivot = list_.pop(0)
for el in list_:
pair = (pivot, el)
yield pair
if len(list_) > 1:
make_all_pairs(list_)
x = make_all_pairs(["a","b","c","d","e"])
for el in x:
print el
('a', 'b')
('a', 'c')
('a', 'd')
('a', 'e')
【问题讨论】:
-
感谢您的回答!