0

我必须:

  1. 要求用户输入文件
  2. 检查文件是否存在
  3. 将数字(来自文件)存储在列表中
  4. 查找列表的长度
  5. 并在没有内置函数的情况下按降序排序

这是我到目前为止所拥有的:

def main():
    try:        
        file=open(input (str("Please enter the name of the file you wish to open:" )),"r")
        A= file.readlines()
        print (A)
        file.close

        n=len(str(A))
        print (n)

        new_list=[]
        for i in range (n):
            for j in range (n-i):
                if A(j-1) < A(j):
                    swap (A(j), A(j-1))
    except IOError as e:
        print("({})".format(e))

我不知道交换后要打印什么。我收到错误(“文件“C:/Python33/project.py”,第 15 行,如果 A(j-1) < A(j): TypeError: 'list' object is not callable")

我应该怎么办?

4

1 回答 1

0

您正在尝试将 alist作为函数调用而不是对其进行索引

if A(j-1) < A(j):
    swap (A(j), A(j-1))

实际上应该是

if A[j-1] < A[j]:
    swap (A[j], A[j-1])

要了解如何索引列表,请通读本教程3.1.3 列表

你更了解 Python 函数,请阅读4.6 定义函数

于 2012-12-15T14:50:26.230 回答