I have two lists list1=['A','B','C'] list2=['1','2','3'] I need a long list (combined by these 2 lists) of length 'n' without
- any same pair consecutively ['A1','A1','C3','B2','B2',.....]
- any same element of list1 consecutively ['A1','A2','A3','B1','B2',.......]
- any same element of list2 consecutively ['A1','B1','C1','A2','B2',.......]
I want the elements of combined list in any order but without duplicates next to each other. In other words, exactly like this for this example, ['A1','B2','C3','A2','B3','C1','A3','B1','C2','A1','B2','C3'.....]
Can someone please help me. I am looking for an answer since 2 days.
Edit:
I tried itertools method products.
newlist = [ n[0]+n[1] for n in list(itertools.product(list1,list2))]
#This gives the exact permutation of elements I need but not in the order I wish.
newlist = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']
#Then, I used nested loops,
#To swap consecutive pairs elements in the newlist for ind,n in enumerate(newlist): while n == newlist[ind-1]: for ind,n in enumerate(newlist): while n == newlist[ind-1]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]
#To swap consecutive list1 elements in the newlist for ind,n in enumerate(newlist): while n[0] == newlist[ind-1][0]: for ind,n in enumerate(newlist): while n[0] == newlist[ind-1][0]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]
#To swap consecutive list2 elements in the newlist for ind,n in enumerate(newlist): while n[1] == newlist[ind-1][1]: for ind,n in enumerate(newlist): while n[1] == newlist[ind-1][1]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]
Apparently, It works well with list with more than 3 elements. But not for the lists with length 3 and 2 respectively.