Python文本文件中的平方数字

时间:2015-03-04 03:20:49

标签: python

我在尝试在文本文件中对数字进行平方时遇到问题。

我的文本文件包含以下内容:

2 8 4 3

7 14 12

9

到目前为止,这是我的代码:

def squares(nums):
    answer = []
    for i in nums:
        answer.append(i*i)
    return answer

def main():
    fname = input("What is the filename? ")
    nums = open(fname, 'r')

    n = []
    for i in nums.readlines:
        n.append(i[:-1])
    j = squares(n)

    print(j)
main()

我不知道问题是什么,我已经尝试过多种方法而且无法解决问题。有人可以帮助/指导我吗?

谢谢...

1 个答案:

答案 0 :(得分:1)

我对您的代码进行了少量更改,以使其实际运行:

def squares(nums):
    answer = []
    for i in nums:
        answer.append(int(i)*int(i)) #<-- here you need integers or floats, not strings
    return answer

def main():
    #fname = input("What is the filename? ")
    nums = open('test.txt', 'r')

    n = []
    for i in nums: n += i.split() #<-- here you need to split line to get individual numbers

    nums.close() #<--you forget to close file after you are done reading from it.

    j = squares(n)

    print(j)

main()

结果是:

[4, 64, 16, 9, 49, 196, 144, 81]