itertools 排列:仅返回特定组合

itertools Permutation: Returning only specific combinations

我想编写一个函数,它接受一个列表(在本例中为端口名称)并打印出它们的所有可能顺序。排列的打印顺序无关紧要,但它们都应以巴拿马 (PAN) 开头。

到目前为止,我已经到了打印出所有排列的地步,但是,我总是无法只打印出以 PAN 开头的那些组合。关于 how/where 更改我的代码的任何想法?

import itertools

portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
 
def permutations(route, ports):
    # write the recursive function here
    # remember to print out the route as the recursion ends
    sum = route + ports
    perms = list(itertools.permutations(sum))
    for perm in perms:
        output = []
        for item in perm:
            output.append(portnames[item])
        
        print(output)

# this will start the recursion with 0 as the first stop
permutations([0], list(range(1, len(portnames))))

您可以从端口名称列表中删除起始端口(代码中的route),然后获取剩余值的所有排列。然后简单地将起始端口添加到每个排列中:

import itertools

portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
 
def permutations(route, ports):
    ports.remove(route)
    perms = itertools.permutations(ports)
    for perm in perms:
        output = [route] + list(perm)
        print(output)

# this will start the route with 'PAN' as the first stop
permutations('PAN', portnames)

输出:

['PAN', 'AMS', 'CAS', 'NYC', 'HEL']
['PAN', 'AMS', 'CAS', 'HEL', 'NYC']
['PAN', 'AMS', 'NYC', 'CAS', 'HEL']
['PAN', 'AMS', 'NYC', 'HEL', 'CAS']
['PAN', 'AMS', 'HEL', 'CAS', 'NYC']
['PAN', 'AMS', 'HEL', 'NYC', 'CAS']
['PAN', 'CAS', 'AMS', 'NYC', 'HEL']
['PAN', 'CAS', 'AMS', 'HEL', 'NYC']
['PAN', 'CAS', 'NYC', 'AMS', 'HEL']
['PAN', 'CAS', 'NYC', 'HEL', 'AMS']
['PAN', 'CAS', 'HEL', 'AMS', 'NYC']
['PAN', 'CAS', 'HEL', 'NYC', 'AMS']
['PAN', 'NYC', 'AMS', 'CAS', 'HEL']
['PAN', 'NYC', 'AMS', 'HEL', 'CAS']
['PAN', 'NYC', 'CAS', 'AMS', 'HEL']
['PAN', 'NYC', 'CAS', 'HEL', 'AMS']
['PAN', 'NYC', 'HEL', 'AMS', 'CAS']
['PAN', 'NYC', 'HEL', 'CAS', 'AMS']
['PAN', 'HEL', 'AMS', 'CAS', 'NYC']
['PAN', 'HEL', 'AMS', 'NYC', 'CAS']
['PAN', 'HEL', 'CAS', 'AMS', 'NYC']
['PAN', 'HEL', 'CAS', 'NYC', 'AMS']
['PAN', 'HEL', 'NYC', 'AMS', 'CAS']
['PAN', 'HEL', 'NYC', 'CAS', 'AMS']