所以我正在研究一个问题,我要创建一个Python类来生成列表的所有排列,并且我遇到了以下问题:
谢谢!
class permutations():
def __init__(self, ls):
self.list = ls
def __iter__(self):
ls = self.list
length = len(ls)
if length <= 1:
yield ls
else:
for p in self.list_all(ls[1:]):
for x in range(length):
yield p[:x] + ls[0:1] + p[x:]
def list_all(self, ls):
length = len(ls)
if length <= 1:
yield ls
else:
for p in self.list_all(ls[1:]):
for x in range(length):
yield p[:x] + ls[0:1] + p[x:]
答案 0 :(得分:0)
只需从self.list_all
致电__iter__
:
class permutations():
def __init__(self, ls):
self.list = ls
def __iter__(self):
for item in self.list_all(self.list):
yield item
def list_all(self, ls):
length = len(ls)
if length <= 1:
yield ls
else:
for p in self.list_all(ls[1:]):
for x in range(length):
yield p[:x] + ls[0:1] + p[x:]