简体   繁体   English

索引错误:列表超出范围(Python)排序问题+枚举()

[英]Index Error: list out of range (Python) Sorting Problem + Enumerate ()

For one of my classes, we are doing debugging activities.对于我的一门课,我们正在进行调试活动。 So for this, we are supposed to Sort a list by locating the minimum value and swapping elements at position i and index_of_min_item.因此,为此,我们应该通过定位最小值并在 position i 和 index_of_min_item 处交换元素来对列表进行排序。

The enumerate function was given as part of the template so I have to include it in the code.枚举 function 作为模板的一部分给出,所以我必须将它包含在代码中。 But I wasn't sure how I should use it if anyone can explain and help me out.但是如果有人可以解释并帮助我,我不确定我应该如何使用它。

I wrote a test case but I kept getting the error message "IndexError: list index out of range" when I tried running it.我写了一个测试用例,但是当我尝试运行它时,我不断收到错误消息“IndexError:list index out of range”。 I have checked many times already but couldn't figure out what's wrong with the code.我已经检查了很多次,但无法弄清楚代码有什么问题。 Can someone help me to identify the problem?有人可以帮我找出问题吗?

import sys
from typing import Iterable, List, TypeVar, Any

T = TypeVar('T')


def swap(values: List, index1: int, index2: int) -> None:
    a = index1
    b = index2
    temp = values[a]
    values[a] = values[b]
    values[b] = temp
    # return values


def get_index_of_min_item(items: List[T]) -> int:
    index_of_min_item = 0
    min_item = items[index_of_min_item]
    for index in range(len(items)):
        cur_item = items[index]
        if cur_item < min_item:
            index_of_min_item = index
            min_item = cur_item
    return index_of_min_item


def sort_items(items: Iterable[T]) -> List[T]:
    n_items=[]
    for pos, items in enumerate(items):
        n_items.append(items)
    for i in n_items:
        index_of_min_item = get_index_of_min_item(n_items[i:-1])
        swap(n_items, n_items[i], n_items[index_of_min_item])
        return n_items

Debugger for sort_items function: sort_items function 的调试器:

import unittest
from typing import TypeVar
from src import sorting

T = TypeVar('T')


class TestSorting(unittest.TestCase):
    def test_sortNum(self):
        self.assertEqual(sorting.sort_items([13, 18, 6, 5, 0]),[0,5,6,13,18])

if __name__ == '__main__':
    unittest.main()

Error Message: File "/Users/Downloads/Sorting/src/sorting.py", line 30, in get_index_of_min_item min_item = items[index_of_min_item] IndexError: list index out of range错误消息:文件“/Users/Downloads/Sorting/src/sorting.py”,第 30 行,在 get_index_of_min_item min_item = items[index_of_min_item] IndexError: list index out of range

Welcome to SO, @vsc.欢迎来到 SO,@vsc。

I have a bit of free time for checking your code and optimize it for you.我有一点空闲时间来检查您的代码并为您优化它。

  • First, your error reason is:首先,您的错误原因是:

    for i in n_items: with n_items = [13, 18, 6, 5, 0] , list index range is [0-4] for i in n_items:当 n_items = [13, 18, 6, 5, 0]时,列表索引范围是 [0-4]

    Start with first item value i=13 => n_items[i:-1] (13 > 4) => IndexError: list index out of range从第一个项目值i=13 => n_items[i:-1] (13 > 4) => IndexError: list index out of range

  • OK, let move to the first suggestion: for i in range(len(n_items)) , this for loop with check with i => [0-4] .好的,让我们来看第一个建议: for i in range(len(n_items)) ,这个 for 循环检查i => [0-4]

    With i=0 => index_of_min_item=3 (wrong, right is 4) => swap(n_items, n_items[i], n_items[index_of_min_item]) will become swap(n_items, 13, 5) => temp = values[a=index1] => n_items[13] => IndexError: list index out of rangei=0 => index_of_min_item=3 (错误,正确的是 4)=> swap(n_items, n_items[i], n_items[index_of_min_item])将变为swap(n_items, 13, 5) => temp = values[a=index1] => n_items[13] => IndexError: 列表索引超出范围

Whatever your code has too many issues here:D无论您的代码在这里有太多问题:D

Python also supports some faster ways to handle these things like: Python 还支持一些更快的方法来处理这些事情,例如:

  • swap: a,b = b,a or items[a], items[b] = items[b], items[a]交换: a,b = b,aitems[a], items[b] = items[b], items[a]

  • get_index_min_value: items.index(min(items[i:])) get_index_min_value: items.index(min(items[i:]))

Try your best to correct your code, that is all my helps.尽力更正您的代码,这就是我的全部帮助。

Here is your homework with some explaining also in python 3+ (items: List[T]) -> int is kinda usless and will make no diference removing it.这是您的作业,在 python 3+ (items: List[T]) -> int有点没用,删除它也没什么区别。

import unittest

def swap(values, index1, index2):
    values_tmp = values[index1]
    values[index1] = values[index2]
    values[index2] = values_tmp

def get_index_of_min_item(items):
    # > len() returns the number of items on a list
    # > range() by deafults uses 0 to start and the end
    # > for a loop shuld be (nº items - 1)

    # > Use of range >
    # >   range(end_index)
    # >   range(start_index, end_index)

    cur_item = items[0]
    out_index = 0
    for index in range(1, len(items)):
        if items[index] < cur_item:
            cur_item = items[index]
            out_index = index
    return out_index

def sort_items(items, descendent=False):
    # n_items = []
    # for pos, item in enumerate(items):
    #     n_items.append(item)
    # > equivelant to :
    n_items = items

    # for i in n_items:
    # > in this case i is not the correct variable,
    # > it is a int() but is conent of the list and
    # > not the index of the content

    last_index = len(n_items) - 1
    for i in range(last_index):
        # > [i:-1] means for x index up to the previus last
        # > [ start_index : end_index ] (end_index is not included)
        lowest_of_reamining = get_index_of_min_item(n_items[i:])
        # > each time get_index_of_min_item() is getting smaller and
        # > smaller list, an offset is needed
        lowest_of_reamining += i

        # swap(n_items, n_items[i], n_items[index_of_min_item])
        # > if swap() ask for a index give a index
        # > not the content of the index
        swap(n_items, i, lowest_of_reamining)

    return n_items

class TestSorting(unittest.TestCase):
    def test_sortNum(self):
        self.assertEqual(
            sort_items(
               [13, 18, 6, 5, 0]
            ), [0, 5, 6, 13, 18]
        )

if __name__ == '__main__':
    unittest.main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM