简体   繁体   中英

Permutations of a list without repeating the first number

I am trying to create a list of sets of 3 items containing all combinations of the items from list where the first number in each set is not repeated.

For example: Set is A,B,C Results: ABC BCA CAB

I have tried using itertools import permutations, but this will give me all possible permutations including one's where the first (left hand) item repeats. For example: ABC ACB

I have used the below code:

from itertools import permutations    
a = ["A123", "A456","A789"]
p = permutations(a)  
  
for j in list(p):
    print(j)

It's not crystal clear what you're trying to accomplish here, but if you literally want one output per n items in your input list, you can just rotate.

from collections import deque
d = deque(["A123", "A456","A789"])
output = []
for x in range(len(d)):
    output.append(list(d.copy()))
    d.rotate()
    
for x in output:
    print(x)

Output

['A123', 'A456', 'A789']
['A789', 'A123', 'A456']
['A456', 'A789', 'A123']

Edit:

If you need only 3 elements per result:

from collections import deque
d = deque(["A123", "A456","A789",'A666','A777'])
output = []
for x in range(len(d)):
    output.append(list(d.copy())[:3])
    d.rotate()
    
for x in output:
    print(x)

Output

['A123', 'A456', 'A789']
['A777', 'A123', 'A456']
['A666', 'A777', 'A123']
['A789', 'A666', 'A777']
['A456', 'A789', 'A666']

You can do the rotation like this too:

a = ["A123", "A456","A789"]
for i in range(len(a)): print (a[i+1:]+a[:i+1])

This will result in:

['A456', 'A789', 'A123']
['A789', 'A123', 'A456']
['A123', 'A456', 'A789']

This will rotate as many elements as you want. Here's another example:

a = ["A12", "A34","A56","A78","A90"]
for i in range(len(a)): print (a[i+1:]+a[:i+1])

Its just moving the position of the i th element to the next position while ensuring all elements of the list are pulled together in the end.

['A34', 'A56', 'A78', 'A90', 'A12']
['A56', 'A78', 'A90', 'A12', 'A34']
['A78', 'A90', 'A12', 'A34', 'A56']
['A90', 'A12', 'A34', 'A56', 'A78']
['A12', 'A34', 'A56', 'A78', 'A90']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM