我正在尝试编写一个程序,从文件中读取数字,然后计算这些数字的平方和。该程序应该提示用户输入文件名并打印平方和。它提供了一个提示,说使用 readlines() 但这对我没有太大帮助。我已经尝试了好几个小时来想出一个有效的代码,但什么也做不了!!!我准备拔头发了!!!这是我的代码:
我的文件代码:
def main():
filename = input("Enter the name for the file: ")
infile = open(filename, 'w')
numList = input('Enter any numbers(seperated by a space): ')
print(numList, file=infile)
main()
我的程序代码:
# function to convert list of strings to real numbers
def toNumbers(nums):
for i in range(len(nums)):
nums[i] = int(nums[i])
# function to square the numbers in a list
def numsquare(nums):
for i in range(len(nums)):
nums[i] = nums[i]**2
# function to add the numbers in the list
def sumList(nums):
total = 0
for i in nums:
total = total + i
return total
# program that pulls numbers from file and computes sum of the square of the numbers
def main():
fname = input("Please enter the name of the file to be opened: ")
nums = open(fname, 'r')
print("The numbers in this list are:")
print(nums)
# Convert strings in list to actual numbers
toNumbers(nums)
# Square the numbers in the list
numsquare(nums)
# Get the sum of the numbers in the list
sumList(nums)
total = sumList(nums)
print()
print("The sum of the numbers from this list is:", total)
main()
如果有人能告诉我我做错了什么,将不胜感激。这是我第一次上计算机科学课,欢迎任何建议。
最佳答案
在不知道文件结构的情况下,我至少可以告诉你你的部分问题是你使用文件句柄作为你的“nums”变量,这不会给你你的内容。
为了从文件中提取数据,您需要在文件句柄上调用 .read() 或 .readline()。
fname = input("Please enter the name of the file to be opened: ")
file = open(fname, 'r')
lines = file.readlines()
lines 现在包含一个列表,其中每个条目都是文件一行的内容
如果您每行有一个数字,您应该能够将每个列表条目的内容转换为一个 int 以获得数字列表。
如果每行有多个数字,则需要在每个列表条目上使用 split() 来提取每个单独的数字。
关于python - 尝试编写一个 python 程序,从文件中读取数字并计算平方和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025358/