Python:从文件中读取数字,将其放入列表中并添加它们,如何解决?

问题描述 投票:-1回答:2

我想读取一个包含3个数字的文件;以空格分隔,然后将数字保存到列表中,并添加列表中的元素,然后在Python中打印总和。但是我在行“ sum + = num [i]”上收到以下错误代码:“ TypeError:+ =不支持的操作数类型:'int'和'list'”

我知道问题出在哪里,但无法解决。您能帮我,怎么办?!

#read file and add the 3 numbers from the file

with open("numbers.txt", "r") as num_file:
    num = []
    for i in num_file:
        i = i.split()
        if i:
            i = [int(j) for j in i ]
            num.append(i)
print("The numbers: ")
print(num)
num_file.close()

print ("Type + if you want to add the numbers!")
add = (input())

if add == "+":
    sum = 0
    for i in range (0,3):
        **sum +=num[i]**
    print(sum)
else:
    print ("Unknown character")
python list int typeerror
2个回答
1
投票

您的错误在这里:

with open("numbers.txt", "r") as num_file:
    num = []
    for i in num_file:          # i is one line of the file
        i = i.split()           # the line is split at spaces into a list
        if i:                   # if anything is in the list
            i = [int(j) for j in i ]  # now i is a list of integers
            num.append(i)       # you add the list of integers to num
print("The numbers: ")

所以num的每个元素都是一个整数列表。

添加它们:

k = 0
for inner_list in num:
    for number in inner_list:
        k += number

您已经完成。为您的variables >>帮助使用更好的名称。


0
投票

除了错误,还有一个is

© www.soinside.com 2019 - 2024. All rights reserved.