在Python中对列表进行排序,而不重复前一项

时间:2014-06-03 06:15:34

标签: python arrays sorting loops organization

我有一个独特的元素组合(A B C D E F)

from itertools import combinations

data = ['A', 'B', 'C', 'D', 'E', 'F'];
comb = combinations(data, 2);

d = [];
for i in comb:
    d.append([i[0], i[1]]);

print d

这回到我身边:

[['A', 'B'], 
 ['A', 'C'], 
 ['A', 'D'],
 ['A', 'E'],
 ['A', 'F'],
 ['B', 'C'],
 ['B', 'D'],
 ['B', 'E'],
 ['B', 'F'],
 ['C', 'D'],
 ['C', 'E'],
 ['C', 'F'],
 ['D', 'E'],
 ['D', 'F'],
 ['E', 'F']]

问题是,如何以一种方式对线进行排序,使得线N不以较简单的方式重复线(N-1)的元素[0]或元素[1] ...:

AB (This line can have any element)
CD (This line can't have A or B)
EF (This line can't have C or D)
AC (This line can't have E or F)
...

2 个答案:

答案 0 :(得分:4)

mylist= [['A', 'B'],
 ['A', 'C'], 
 ['A', 'D'],
 ['A', 'E'],
 ['A', 'F'],
 ['B', 'C'],
 ['B', 'D'],
 ['B', 'E'],
 ['B', 'F'],
 ['C', 'D'],
 ['C', 'E'],
 ['C', 'F'],
 ['D', 'E'],
 ['D', 'F'],
 ['E', 'F']] 


a=mylist[:] #this used to assign all elements to a so u have ur mylist safe    
b=[]
b.append(a[0]) #this appends the first list in the list
del a[0]  #now deleting appended list        
while len(a)>0:
    for val,i in enumerate(a):# enumerte gives index and value of list
        if len(set(b[len(b)-1]).intersection(set(i)))==0: # this checks intersection so that both list should not have same elements
            b.append(a[val])
            del a[val]
print b

#output [['A', 'B'], ['C', 'D'], ['E', 'F'], ['A', 'C'], ['B', 'D'], ['C', 'E'], ['D', 'F'], ['A', 'E'], ['B', 'C'], ['D', 'E'], ['A', 'F'], ['B', 'E'], ['C', 'F'], ['A', 'D'], ['B', 'F']]

答案 1 :(得分:2)

使用this answer中的邻域生成器,您可以获得循环中的上一个,当前和下一个元素,以便您可以比较它们。然后你可以做这样的事情

from itertools import combinations

# Credit to Markus Jarderot for this function
def neighborhood(iterable):
    iterator = iter(iterable)
    prev = None
    item = iterator.next()  # throws StopIteration if empty.
    for next in iterator:
        yield (prev,item,next)
        prev = item
        item = next
        # this can be written like this also prev,item=item,next
    yield (prev,item,None)

data = ['A', 'B', 'C', 'D', 'E', 'F'];
comb = combinations(data, 2);

d = [];
for prev, item, next in neighborhood(comb):
    # If prev and item both exist and neither are in the last element in d
    if prev and item and not any(x in d[-1] for x in item):
        d.append([item[0], item[1]])
    elif item and not prev: # For the first element
        d.append([item[0], item[1]])

print d

打印

[['A', 'B'],
 ['C', 'D'],
 ['E', 'F']]

我知道这可能不是你需要的100%,但它应该能够让你到达你想要的地方