简体   繁体   English

Python:从文件列表中读取变量以计算方程式

[英]Python: read a variable from list of a file in order to calculate equation

I have to calculate different equation (we assume 3 reactions). 我必须计算不同的方程式(我们假设3个反应)。 Each one uses a different variable and I have to read this variable from a file list.txt . 每个变量使用一个不同的变量,我必须从文件list.txt读取此变量。 So my idea is: 所以我的想法是:

f = open('list.txt')
lines = f.readlines()

k1 = lines[0]

r1 = k1 * 2  # this is first equation 
print(r1) 

k2 = lines[1]  # second equation
r2 = k2 * 2
print(r2) 

k3 = lines[2]
r3 = k3 * 3
print (r3) 

My list is: 我的清单是:

1
2
3

but this code prints first line two times, the second line three times and so on. 但是此代码将第一行打印两次,第二行打印三次,依此类推。 Instead, I want that k1 , k2 and k3 as a variable in order to obtain in this case: 相反,我希望将k1k2k3作为变量,以便在这种情况下获得:

r1 = 2
r2 = 6
r3 = 9.

How can I do to obtain this result? 如何获得此结果?

it's clear here that if you read a file with readlines(), it will return a string. 很显然在这里 ,如果你阅读readlines方法文件(),它会返回一个字符串。 So, when you want to do a math calculation, you need to convert it to integer first 因此,当您要进行数学计算时,需要先将其转换为整数

f=open('list.txt')
lines=f.readlines()

k1=int(lines[0]) # convert to integer

r1=k1*2  #this is first equation 
print (r1) 

k2=int(lines[1])  #second equation
r2=k2*2
print (r2) 

k3=int(lines[2])
r3=k3*3
print (r3)

when you use the * operator on strings, you multiple them. 在字符串上使用*运算符时,会将它们乘以多个。 for example: "a"*3 will be "aaa" and when you use it on numbers you perform the math operation. 例如: "a"*3将是"aaa" ,当您在数字上使用它时,将执行数学运算。 for example: 3*6=18 例如: 3*6=18

each line is string, so you need to cast the line to int: int(line) . 每行都是字符串,因此您需要将该行强制转换为int: int(line)

also, you should consider use the map function. 另外,您应该考虑使用地图功能。

it will make your life easier. 它将使您的生活更轻松。

map perform given function on every item in the list. map对列表中的每个项目执行给定的功能。

for example: 例如:

result = list(map(lambda x: int(x) * 3, lines))

it takes every item in the list, cast it to int, and multiply it by 3. 它采用列表中的每个项目,将其强制转换为int,然后乘以3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM