【问题标题】:Python Beginner Question about practice problem关于练习题的Python初学者问题
【发布时间】:2020-11-24 23:46:27
【问题描述】:

我正在学习 python,需要帮助来理解我做错了什么。我要完成的任务是创建一个从 1 到 100 的整数列表,然后根据这些数字创建另外两个列表,并通过打印这两个列表来完成。但是,我无法将第二个列表写入名为 target list.txt 的文件。谁能告诉我我做错了什么?

num1 = input("Please Input a name for the file ending it with .txt. ")
numb_list = open(num1, "w")
mylist = []


def integer_list():
    for numbers in range(1, 101):
        mylist.append(numbers)
        numb_list.write(str(numbers) + "\n")
        print(numbers, end="\n")


integer_list()
print(mylist)
numb_list.close()


def target_list():
    for numbers2 in range(25, 75):
        mylist.append(numbers2)
        target_list.write(numbers2+ "\n")
        print(numbers2, end="\n")


target_list()
print(mylist)
target_list.close()

【问题讨论】:

  • target_list.write(numbers2+ "\n") 是这一行导致错误吗?可能是因为您试图将字符串和整数一起写入,请将整数转换为字符串
  • 你在哪里放了target_list.write(numbers2+ "\n"),你希望这行代码做什么?您说“我无法将第二个列表写入名为 target list.txt 的文件”。你有任何关于如何写入文件的参考资料吗?我认为你应该审查它。或者:在你的程序顶部,你在哪里做numb_list = open(num1, "w") - 用你自己的话来说,这行的目的是什么?

标签: python python-3.x


【解决方案1】:
  1. 您没有打开第二个文件。您使用了函数名称 target_list 而不是新文件。这就是导致您的程序失败的原因。
  2. 不要在函数中使用全局状态。您可以在每次通话时return 一个新列表。这可以防止函数的一次调用影响下一次调用的行为。
  3. 使用函数参数允许函数的行为略有不同。这使得函数更实用,避免重复代码。
def integer_list(start, end):
    file_name = input("Please Input a name for the file ending it with .txt. ")
    num_list = []
    num_file = open(file_name, "w")
    for num in range(start, end):
        num_list.append(num)
        num_file.write(str(num) + "\n")
        print(num)
    num_file.close()
    return num_list


num_list1 = integer_list(1, 101)
print(num_list1)

num_list2 = integer_list(25, 75)
print(num_list2)

【讨论】:

  • 这对我来说很有意义。谢谢你的解释。
【解决方案2】:

您没有打开第二个文件。 target_list.write 是您遇到错误的地方,原因是因为 target_list 是一个函数而不是文件。

【讨论】:

    【解决方案3】:

    scope 有多个问题。

    这里是固定代码:

    num1 = input("Please input a name for the file ending it with .txt ")
    numb_list = open(num1, "w")
    
    global mylist
    mylist = []
    
    
    def integer_list():
        for numbers in range(1, 101):
            mylist.append(numbers)
            numb_list.write(str(numbers) + "\n")
            print(numbers)#, end="\n")
    
    
    integer_list()
    print(mylist)
    #numb_list.close()
    
    
    def target_list():
        for numbers in range(25, 75):
            mylist.append(numbers)
            numb_list.write(str(numbers)+"\n") # Needed to be a string
            print(numbers)#, end="\n")
    
    
    target_list()
    print(mylist)
    numb_list.close()
    

    【讨论】:

      猜你喜欢
      • 2013-01-08
      • 1970-01-01
      • 2021-02-19
      • 2011-01-12
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多