我有一个Python列表,表示图形的边缘,我想对它进行排序,以便第一个列表的第二个值与下一个列表的第一个值相同。例如,我有这个列表:
[('AT', 'TG'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GC', 'CA'), ('TG', 'GC'), ('CA', 'AA'), ('AA', 'AT')]
我想改变顺序,以便列表如下:
[('AT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GT', 'TG'), ('TG', 'GC'), ('GC', 'CA'), ('CA', 'AA'), ('AA', 'AT')]
我该怎么做?
答案 0 :(得分:1)
也许这有帮助。它打印所有可能的"排序":
from collections import defaultdict
l = [('AT', 'TG'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GC', 'CA'), ('TG', 'GC'), ('CA', 'AA'), ('AA', 'AT')]
lookup = defaultdict(set)
for k, v in l:
lookup[k].add(v)
def sort(l, s):
k = l[-1][1]
pairs = set([(k, v) for v in lookup[k]]) - s
if len(pairs) == 0:
return [l]
results = set()
for k, v in pairs:
results.update(sort(l + ((k, v), ), s | set([(k, v)])))
return results
results = sort((('AT', 'TG'), ), set([('AT', 'TG')]))
for result in results:
print list(result)
输出:
[(' AT',' TG'),(' TG',' GG'),' GG& #39;,' GC'),(' GC',' CG'),(' CG',' GT&# 39;),(' GT',' TG'),(' TG',' GC'),' GC& #39;,' CA'),(' CA',' AA'),(' AA',' AT&# 39)]
[(' AT',' TG'),(' TG',' GC'),(' GC& #39;,' CA'),(' CA',' AA'),(' AA',' AT&# 39)]
[(' AT',' TG'),(' TG',' GC'),(' GC& #39;,' CG'),(' CG',' GT'),(' GT',' TG&# 39;),(' TG',' GG'),(' GG',' GC'),' GC& #39;,' CA'),(' CA',' AA'),(' AA',' AT&# 39)]
[(' AT',' TG'),(' TG',' GG'),' GG& #39;,' GC'),(' GC',' CA'),(' CA',' AA&# 39;),(' AA',' AT')]