我有很多数据表单,我想将浮点数提供给其他函数。为此,我创建了一个函数Lsym(s,n,N =' 11a'),它为我部分地完成了这项工作。 我想访问下面数据右侧的浮点
Lsym['11a'][1][2]=1.057599244591
Lsym['11a'][2][2]=1.127354242069
Lsym['11a'][3][2]=1.090644807038
Lsym['11a'][4][2]=1.052410518255
Lsym['11a'][5][2]=1.02815187087
Lsym['11a'][2][4]=0.8209366139554
Lsym['11a'][3][4]=0.8949278089063
Lsym['11a'][4][4]=0.9429984866328
Lsym['11a'][5][4]=0.970256549013
Lsym['11a'][3][6]=0.8929614099822
Lsym['11a'][4][6]=0.9434221639356
Lsym['11a'][5][6]=0.970721596782
Lsym['11a'][4][8]=1.053427474878
Lsym['11a'][5][8]=1.02816330898
Lsym['11a'][5][10]=1.03597753138
.....
我写的代码是
def Lsym(s,n,N = '11a'):
f = open("path",'r')
for item in f:
if item.split('=')[0][6:-8] == N:
if s == int(item.split('=')[0][-5]):
if n == int(item.split('=')[0][-2]):
id1 = float(item.split('=')[1][:-1])
if n == int(item.split('=')[0][15:17]):
id1 = float(item.split('=')[1][:-1])
return id1
这是
的输出sage: Lsym(1,2)
sage: 1.057599244591
sage: Lsym(3,6)
sage: 0.8929614099822
但是当我打电话时
sage: Lsym(5,10)
ValueError: invalid literal for int() with base 10: '2]'
我该如何解决这个问题?或者有没有更好的方法来访问这些浮动值?特别是,我如何访问
Lsym(5,10)?
感谢您的时间和帮助。
答案 0 :(得分:1)
您遇到的问题是您在字符串中使用位置索引。因此,当您转到两位数时(' 10'),您的选择会出错
在" ["
上再次拆分的一个快速解决方法def Lsym(s,n,N = '11a'):
f = open("path",'r')
for item in f:
if item.split('=')[0].split('[')[1][1:-2] == N:
if s == int(item.split('=')[0].split('[')[2][:-1]):
if n == int(item.split('=')[0].split('[')[3][:-1]):
id1 = float(item.split('=')[1][:-1])
return id1
答案 1 :(得分:1)
这里的解决方案也适用于s和n的数字大于9。
def Lsym(s,n,N = '11a'):
with open("path",'r') as f:
for item in f:
[head,number] = item.split("=")
[_, first,second,third] = head.replace('[',' ').replace(']',' ').split()
if first.strip('\'') == N and int(second) == s and int(third) == n:
return number.strip()