如果我有一个包含五个项目的列表,并且我想获得该列表的每个排列,那么如何保持第一个和最后一个项目相同?
同样,五个项目的列表将导致列表的120个排列,其中该列表中将有六个项目,但第一个和最后一个项目将是相同的。以下是我到目前为止所做的工作。任何帮助将不胜感激。
from itertools import permutations
airportlist = ["airport1", "airport2", "airport3", "airport4", "airport5"]
permlist = permutations(airportlist, 5)
print(permlist)
print(list(permlist))
for i in list(permlist):
newlist = (list(i))
print(newlist)# getting e.g. ['airport1', 'airport5', 'airport2', 'airport4', 'airport3']
print(list(i)[0]) # getting (to continue above example) airport1
newerlist = (list(i).append((list(i)[0])))
print(newerlist)#getting None but want ['airport1', 'airport5', 'airport2', 'airport4', 'airport3', 'airport1']
这可能吗?
答案 0 :(得分:4)
如果我找到了你,你想让第一个和最后一个机场与原始列表保持一致,并生成两者之间元素的排列。在这种情况下,您可以执行类似下面的操作,其中您只为中间的元素生成排列:
>>> from itertools import permutations
>>> airports = ["airport1", "airport2", "airport3", "airport4", "airport5"]
>>> [airports[:1] + list(x) + airports[-1:] for x in permutations(airports[1:-1])]
[['airport1', 'airport2', 'airport3', 'airport4', 'airport5'], ['airport1', 'airport2', 'airport4', 'airport3', 'airport5'], ['airport1', 'airport3', 'airport2', 'airport4', 'airport5'], ['airport1', 'airport3', 'airport4', 'airport2', 'airport5'], ['airport1', 'airport4', 'airport2', 'airport3', 'airport5'], ['airport1', 'airport4', 'airport3', 'airport2', 'airport5']]
<强> 修改 强>:
重新阅读你的问题,我想你可能想要创建排列,开始和结束机场相同,中间的值得到置换,这将非常简单:
>>> combos = [list(x) + [x[0]] for x in permutations(airports)]
>>> for x in combos: print x
['airport1', 'airport2', 'airport3', 'airport4', 'airport5', 'airport1']
['airport1', 'airport2', 'airport3', 'airport5', 'airport4', 'airport1']
...
...
['airport5', 'airport4', 'airport3', 'airport1', 'airport2', 'airport5']
['airport5', 'airport4', 'airport3', 'airport2', 'airport1', 'airport5']
答案 1 :(得分:1)
嗯,好吧,将每个列表的第一项附加到每个列表中。
from itertools import permutations
airportlist = ["airport1", "airport2", "airport3"]
perms = permutations (airportlist)
newperms = [list (x) + [x[0]] for x in perms]
for element in list (newperms):
print element
结果是:
['airport1', 'airport2', 'airport3', 'airport1']
['airport1', 'airport3', 'airport2', 'airport1']
['airport2', 'airport1', 'airport3', 'airport2']
['airport2', 'airport3', 'airport1', 'airport2']
['airport3', 'airport1', 'airport2', 'airport3']
['airport3', 'airport2', 'airport1', 'airport3']
答案 2 :(得分:0)
我想你想要的是:
[airportlist[:1] + list(i) + airportlist[:1] for i in permutations(airportlist[1:])]