2017-09-17 24 views
0

我有很多数据表单,我想将浮点数提供给其他函数。为此,我创建了一个函数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

可能是因为它的两个数字 –

+0

是的,这就是为什么我有一个单独的案例如果n == INT(item.split( '=')[0] [15:17]),但它仍然犯规工作。 – Kumarm

回答

1

这里以数字大于9也有效的解决方案为s和n。

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() 
+0

谢谢..此解决方案也适用... – Kumarm

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