对列表中的值执行数学运算

时间:2021-03-29 00:12:50

标签: python list math floating-point

我正在尝试将列表中的值添加到外部整数。

该列表来自 .text 文件 "apiresp"

APIlines = []      # Declare an empty list named APIlines.

with open ('apiresp.txt', 'rt') as myfile: # Open airesp.txt for reading text data.
     
    
    for APIline in myfile:         # For each line, stored as myfile,       
        
        APIlines.append(APIline)       # add its contents to APIlines.          
    
        hpa = (APIlines[5]) 

# function to extract numbers from string
s = [float(s) for s in re.findall(r'-?\d+\.?\d*', hpa)] 

res = [float(ele) for ele in s]

b = []

for item in s:
    b.append(float(item)) # convert the string to a float which we can use in mathematical operations

res1 = res + 1

print(res1)

我的印象是第 10 行会将对象从列表中“提取”为浮点数,因此我们可以用于数学运算,但我对此很陌生,所以如果它是一个 愚蠢的问题/假设。

它返回以下错误:

line 36, in <module>
      res1 = res + 1 
TypeError: can only concatenate list (not "int") to list

这是一个迟到的学校项目,所以任何帮助将不胜感激。谢谢各位:)

2 个答案:

答案 0 :(得分:1)

改变你的线路:

res1 = res + 1

到:

res1 =[x+1 for x in res]

with 列出用于连接列表的 (+) 运算符:

l=[1,2,3]
x=[4,5,6]
print(l+x)
>>>[1, 2, 3, 4, 5, 6]

和 (*) 用于重复列表,如:

print(l*3)
>>>[1, 2, 3, 1, 2, 3, 1, 2, 3]

要递增列表值,您需要在循环内或使用推导式表达式一项一项地处理列表项。

答案 1 :(得分:0)

使用列表推导式:res1 = [item+1 for item in res] 列表的 + 运算符进行连接,也就是将列表连接在一起。