【问题标题】:Passing Argument in Python在 Python 中传递参数
【发布时间】:2016-02-08 06:51:44
【问题描述】:

我是 python 新手,正在尝试编写作业代码,但遇到了一些麻烦。

到目前为止,我试图做的是import 一个文件到程序中,return 它到main()

我创建了另一个函数调用 print_names() 来打印列表中的名称,每行一个单行距,我尝试按字母顺序对文件中的内容进行排序(我被要求在 main() 中进行排序) .

那么现在我要做的是将该排序列表传递给另一个函数,以便我可以将它们放入一个新的输出文件中。

def main():
    names_in()                          # This function import the file and read all the content and put the content into a list.   
    print_names(names_in)               # Before the names are sorted.    
    names_sorted = sorted(names_in())   # Sort the list of names.   

    for item in names_sorted:           
        print(item)       

def names_in():
    infile = open('names.txt','r')
    names_list = []                     # empty list.
    names = infile.readline()           # read contents.

    # loop for continue to read.
    while names != '':
        names = infile.readline()       # continue to the next name.
        names = names.rstrip('\n')      # return a copy of the string which all \n has been stripped from the end of the string.
        names_list.append(names)        # write names in the file into a list.
    return names_list                   # return the list back to the function. 

    infile.close()                      # close the file.

def print_names(names_in):              # This function will print out the names in the list one per line, single-spaced.
    for item in names_in():
        print(item)


main()

【问题讨论】:

  • 还有……具体的问题是什么?

标签: python list arguments sorted


【解决方案1】:

当你从函数返回一个值时,你需要将它分配给一个变量,否则,你会忽略它(有时会这样做)。完全未经测试的重写:

def main():
    names = names_in()            # This function import the file and read all the content and put the content into a list.   
    print_names(names)            # Before the names are sorted.    
    names_sorted = sorted(names)  # Sort the list of names.   

    for item in names_sorted:           
        print(item)       

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2019-12-10
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多