这是我在这里的第一个问题=): 我的问题是标题中所述的内容。我想简单地用2个元素对元组列表进行排序。它应该与sort一起工作,但它仍然返回未排序的List,...它似乎什么都不做。 输入:
#"L =[(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5)]" Its an example.
for line in stdin:
L = [int(i) for i in line.split()]
n = L[0]
V = [i for i in range(n)]
edgelist = L[1:]
EDGE = [(edgelist[i],edgelist[i+1]) for i in range(0,len(edgelist)-1,2) ]
mK = missingKnots(edgelist)
EDGE = sorted(EDGE)
EDGE = list(set(EDGE))
输出:
[(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5)]
应该是:
[(0, 1), (0, 4), (0, 6), (2, 5), (4, 6), (5, 7)]
未分类=(。 谢谢你的阅读!
答案 0 :(得分:5)
排序并返回新列表:
>>> L =[(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5)]
>>> sorted(L)
[(0, 1), (0, 4), (0, 6), (2, 5), (4, 6), (5, 7)]
按位排序:
>>> L.sort()
>>> L
[(0, 1), (0, 4), (0, 6), (2, 5), (4, 6), (5, 7)]
之后不要执行set()
。集合是无序的。
>>> list(set(L))
[(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5)] # now it's messed up again.
理想情况下,要排序和删除重复项:
>>> L = [(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5), (0, 1)]
>>> sorted(set(L))
[(0, 1), (0, 4), (0, 6), (2, 5), (4, 6), (5, 7)]
答案 1 :(得分:1)
使用lambda表达式,您可以自定义排序规则。
EDGE = [(0, 1), (4, 6), (5, 7), (0, 6), (0, 4), (2, 5)]
EDGE = sorted(EDGE, key=lambda x: (x[0],x[1]) )
print EDGE
结果:
[(0, 1), (0, 4), (0, 6), (2, 5), (4, 6), (5, 7)]