Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用字母字符串对列表进行排序_Python_List_Sorting - Fatal编程技术网

Python 使用字母字符串对列表进行排序

Python 使用字母字符串对列表进行排序,python,list,sorting,Python,List,Sorting,我试图使用以下字符串对仅包含小写字母的列表进行排序: alphabet = "abcdefghijklmnopqrstuvwxyz". 这不需要使用sort,只需要O(n)复杂度。 我来到这里: def sort_char_list(lst): alphabet = "abcdefghijklmnopqrstuvwxyz" new_list = [] length = len(lst) for i in range(length): new_list.insert(alphabet

我试图使用以下字符串对仅包含小写字母的列表进行排序:

alphabet = "abcdefghijklmnopqrstuvwxyz". 
这不需要使用sort,只需要O(n)复杂度。 我来到这里:

def sort_char_list(lst):
alphabet = "abcdefghijklmnopqrstuvwxyz"
new_list = []
length = len(lst)

for i in range(length):
    new_list.insert(alphabet.index(lst[i]),lst[i])
    print (new_list)

return new_list
对于此输入:

m = list("emabrgtjh")
我明白了:

['e']
['e', 'm']
['a', 'e', 'm']
['a', 'b', 'e', 'm']
['a', 'b', 'e', 'm', 'r']
['a', 'b', 'e', 'm', 'r', 'g']
['a', 'b', 'e', 'm', 'r', 'g', 't']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'j']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'h', 'j']
['a', 'b', 'e', 'm', 'r', 'g', 't', 'h', 'j']

看起来一路上出了点问题,我似乎不明白为什么。。如果有人能启发我,那就太好了

您正在寻找桶排序。在这里:

def sort_char_list(lst):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    # Here, create the 26 buckets
    new_list = [''] * len(alphabet)

    for letter in lst:
        # This is the bucket index
        # You could use `ord(letter) - ord('a')` in this specific case, but it is not mandatory
        index = alphabet.index(letter)
        new_list[index] += letter

    # Assemble the buckets
    return ''.join(new_list)

至于复杂性,由于
字母表
是一个预定义的固定大小字符串,因此在其中搜索一个字母最多需要26次操作,即
O(1)
。因此,总的复杂性是
O(n)

您正在插入
新列表中
字母表的索引处
字符串。。。这不会对列表进行排序。如果每次迭代都要搜索列表(这是
索引所必须做的),这不是O(n)。为什么不呢?看起来它一直工作到i=6。如果你能解释得更多,我会很高兴的(:试着打开一个python shell并写:
x=[]
,然后
x.insert(42,“foo”)
。你不会看到“foo”在
x
的第42个条目中,您将看到一些其他内容…这是否需要处理重复的内容?非常感谢,我很高兴学习新的东西和方法来处理问题。我对这一点仍然很陌生,很高兴这个社区能够与伟大的人们分享想法。再次感谢!