代码之家  ›  专栏  ›  技术社区  ›  Kumarm

使用函数访问部分数据?

  •  0
  • Kumarm  · 技术社区  · 8 年前

    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)?
    

    谢谢你的时间和帮助。

    2 回复  |  直到 8 年前
        1
  •  1
  •   paperazzo79    8 年前

    这里的解决方案也适用于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()
    
        2
  •  1
  •   BA.    8 年前

    您的问题是在字符串中使用位置索引。因此,当您转到两位数(“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