Python索引器处理

2024-10-01 00:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

def kindDetector(list):
    for i in range(0,len(list)):
        if type(list[i]) != type('a'):
            return 0
    return 1

def findWords(list,i):
    if i == 0:
        return list[0]
    if list[i] < findWords(list,i-1):
        return list.pop(i)
    else:
        return list.pop(i-1)

def sortWords(list,i):
    result=[]
    while i >= 0:
        result.append(findWords(list,i))
        i -=1
    print(result)


list = input('Enter your words, with a space between.\t').split()
i = len(list)-1
if kindDetector(list):
    sortWords(list,i)

但在这里,我只能输入2个单词,当我尝试使用3时,会发生这种情况:

Traceback (most recent call last):
  File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 26, in <module>
    sortWords(list,i)
  File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 18, in sortWords
    result.append(findWords(list,i))
  File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 10, in findWords
    if list[i] < findWords(list,i-1):
IndexError: list index out of range

Tags: inpyreturnifdeflineresultusers
1条回答
网友
1楼 · 发布于 2024-10-01 00:16:28

您将BubbleSortSelectionSort混合(即,比较相邻项并尝试一次移动一个,直到列表排序为止)(即,从未排序的列表中找到最小的项,并将其附加到结果列表的前面)。你知道吗

这里还有一些问题:

  • Python通过引用传递变量,这意味着函数接收原始列表的句柄而不是副本。如果您在迭代时更改列表(您的pop()调用所做的),您将遇到索引错误。

  • 你的findWords函数有缺陷。从后向前迭代,并检查当前元素是否在词典上比其前一个元素小(即leftneighbor)。您可能想将pop调用更改为return语句,是吗?

我已经很快实现了一些基本的排序算法(没有错误处理、类型比较器的使用等):

def is_list_of_strings(lst):
    for i in range(0,len(lst)):
        if type(lst[i]) not in (str, unicode):
            return False
    return True

def is_sorted(lst):
    if len(lst) < 2:
        return True
    for i in range(len(lst) - 1):
        if not lst[i] < lst[i + 1]:
            return False
    return True

def selection_sort(lst):
    l = lst[:] # Copy!
    r = []
    while len(l):
        r.append(l.pop(l.index(min(l))))
    return r

def insertion_sort(lst):
    l = lst[1:] # Copy!
    r = [lst[0]]
    for e in l:
        inserted = False
        for w in r:
            if e < w:
                r.insert(r.index(w), e)
                inserted = True
                break
        if not inserted:
            r.append(e)
    return r

def bubble_sort(lst):
    l = lst[:] # Copy!
    while not is_sorted(l):
        for i in range(len(l) - 1):
            if l[i] > l[i + 1]:
                tmp = l[i]
                l[i] = l[i + 1]
                l[i + 1] = tmp
    return l

if __name__ == '__main__':
    lst = ['aaa', 'aba', 'aab', 'baz', 'bar']

    print('Valid list of strings?', is_list_of_strings(lst))
    print(lst, is_sorted(lst))

    bbl = bubble_sort(lst)
    ins = insertion_sort(lst)
    sel = selection_sort(lst)

    print(bbl, is_sorted(bbl))
    print(ins, is_sorted(ins))
    print(sel, is_sorted(sel))

看看它们,试着理解它们,并在网上阅读这三种技巧。然后尝试使用自己的函数重新实现它们。享受编码的乐趣:)

相关问题 更多 >