0

首先,我有这个功能:

def change_pos(a, b):
  temp = a
  a = b
  b = temp
  print 'Done'

我在另一个函数中调用它,但它只是打印“完成”并且什么都不做。我直接写代码:

a = 1
b = 2
temp = a
a = b
b = temp

它工作正常。这里有什么建议吗?其次,这是我的代码

def check_exception(list):
    for element in list:
    # Take list of numbers
    # \s*: Skip space or not (\t\n\r\f\v), \d: Number [0-9]
    # ?: Non-capturing version of regular parentheses
        first = re.compile("\s*(?:\[)(\d+)\s*(?:,)").findall(element)
        last = re.compile("\s*(?:,)(\d+)\s*(?:\])").findall(element)
    # Convert string to integer
        first_int = map(int, first)
        last_int = map(int, last)

    # Check and code above works
        i = 0
        print first_int[i]
        change_pos(first_int[i],first_int[i+1])
        print first_int[i+1]
        print len(first_int)
        #print type(first_int[0])
    # Sort
        # Error: list index out of range at line 47 and more
        i = 0
        while i < len(first_int):
            if first_int[i] > first_int[i+1]:
                change_pos(first_int[i], first_int[i+1])
                change_pos(last_int[i], last_int[i+1])
            i += 1
    # Check exception
        j = 0
        while j < len(last_int):
            if last_int[j] < first_int[j+1]:
                return false
                break
            else:
                j += 1
                continue
            return true

我看到:IndexError: list index out of range at conditions after #Error 感谢您的帮助。:)

4

3 回答 3

3

您的change_pos函数没有任何用处,因为它只交换函数内部的变量,而不是用于调用函数的变量。实现您想要的一种方法是:

def change_pos(a, b):
    print 'DONE'
    return b, a

然后使用它变成:

a, b = change_pos(a,b)

甚至没有函数:

a, b = b, a

其次,我相信您可以自己弄清楚为什么会出现索引错误。但无论如何,这就是为什么。last_int数组是零索引的,您正在使用while 循环中的长度。现在想象last_int长度为 5。这意味着它的索引值范围为 0-4。在循环的最后一次迭代中,您尝试last_int[5]在 if 语句 ( last_int[j+1]) 中访问,这当然会给您一个索引错误。

于 2013-10-06T06:40:09.400 回答
1

您可能被告知变量是内存中的位置,其中包含数据。这不适用于 Python。变量只是指向对象的名称。

因此,您不能在 Python 中编写函数,例如您尝试编写的 change_pos 函数,因为您更改的名称将是函数中使用的名称,而不是调用时使用的名称。

而不是这个:

a = 1
b = 2
change_pos(a, b)

你必须这样做:

a = 1
b = 2
a, b = change_pos(a, b)

该函数需要如下所示:

def change_pos(a, b):
    return b, a

这给你一个提示,有一种更简单的方法,而且确实有。你可以这样做:

a = 1
b = 2
a, b = b, a

所以根本不需要函数。

由于您实际上想要交换列表中的整数,因此可以创建如下函数:

def change_pos(lst, p):
    lst[p], lst[p+1] = lst[p+1], lst[p]

但我认为这不会显着增加代码的可读性。

此外,您对 this 的使用以注释为前缀#sort。但是您的代码没有排序。这有点像半途而废的冒泡排序,但我不知道你为什么要这样做。

于 2013-10-06T06:41:39.960 回答
-2

数字在 python 中是不可变的。当您将它们传递给函数时,该函数使用变量的副本。如果您尝试使用诸如列表之类的可变类型,这可能会很棘手。但是 python 的这个函数包含了一些巧妙的语法技巧。

   a, b = b, a

这可以交换两个变量,而不需要任何额外的功能。

于 2013-10-06T06:44:23.123 回答