2017-08-25 127 views
-4

任何人都可以请向我解释为什么从一个排序列表中导出一个不排序的集合?当对一个排序列表进行排序时,输出集合不排序

list.sort()应该按照原样对列表进行排序。 set(list)应该返回列表的唯一值,就像它一样。

但为什么结果集不能排序?我是否需要创建一个集合,将其重新转换为list2,然后对list2进行排序?

(使用Python 2.7.6)

代码:

def longest(s1, s2): 
    list = [] 
    s = s1 + s2 
    for letter in s: 
     list.append(letter) 
    print list 
    list.sort() 
    print list 
    unique = set(list) 
    print unique 
    s4 = "" 
    for item in unique: 
     s4 = s4 + item 
    print s4 
    return s4 

控制台输出:

['a', 'r', 'e', 't', 'h', 'e', 'y', 'h', 'e', 'r', 'e', 'y', 'e', 's', 't', 'h', 'e', 'y', 'a', 'r', 'e', 'h', 'e', 'r', 'e'] 
['a', 'a', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'h', 'h', 'h', 'h', 'r', 'r', 'r', 'r', 's', 't', 't', 'y', 'y', 'y'] 
set(['a', 'e', 'h', 's', 'r', 't', 'y']) 
aehsrty 
+1

设置的是没有顺序的,所以为什么要实施返回它们排序的功能?如果你想要一个有序集合,使用'sorted(set(x))',如下所述:https://stackoverflow.com/questions/15181867/understanding-the-set-function –

+2

集合按照定义是无序的 –

回答

0

集是通过性质,无序的数据结构。对于Python 2.7,集合不一定会保持顺序,但在Python 3.x中,顺序应该保持不变。

0

仅设置可确保其具有唯一的元素,并且不会默认进行排序。

你需要使用排序(集(列表))

+0

谢谢,修正它从手机打字。 – JRG

相关问题