gpt4 book ai didi

python - 元组的排序列表不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:25 25 4
gpt4 key购买 nike

这是我的第一个问题 =):我的问题是标题中所述。我想简单地对包含 2 个元素的元组列表进行排序。它应该与排序一起工作,但它仍然返回未排序的列表,......它似乎什么都不做。输入:

#"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)]

未排序 =(.感谢阅读!

最佳答案

排序并返回新列表:

>>> 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)]

关于python - 元组的排序列表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34034075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com