2016-04-25 88 views
0

我有一個文件從讀取,看起來像:分配列表蟒對象

0.0017224129699045 0.0006501069699993 0.9998957781816742 
    0.1990018751753198 0.0008531972943402 0.0001365339587167 
    0.3985306090674854 0.0004447825187626 0.9994454487115476 
    0.5997635306734566 0.0007689624538330 0.0001887505556155 
    0.8014083650919446 0.0007156269856168 0.9995317401042954 
    0.1999636426048639 0.1995427045657650 0.0017775030876521 

每列顯示一個原子的座標。我想座標分配給定義爲在python對象的原子:

# The parser 
#!/usr/bin/python3 
def get_pos(): 
    with open("CONTCAR", "r") as finp: 
     for line in finp: 
      for _ in range(6): 
       sdata = finp.readline() 
       tpos.append(sdata.split()) 

    print(tpos) 

並調用函數是:

#!/usr/bin/python3 
import parsepos 

class Atom: 
    count = 0 

    def __init__(self, name, pos=[], vel=[]): 
     self.name = name 
     self.pos = pos 
     self.vel = vel 
     Atom.count += 1 
     # self.parse = parsepos.get_pos() 
parsepos.get_pos() 

mcwe,示出的原子被正確列出,在list tpos,但我不知道如何將這些值分配給atom.pos

請幫忙。

+0

使用'#!/ usr/bin/env python3'而不是'#!/ usr/bin/python3'會發現Python解釋器,無論它安裝在哪裏... – linusg

+1

爲什麼不是'atom.pos = whatever' ? –

+0

'Atom.pos = parsepos.get_pos() print(Atom.pos)'yeilds'none' – BaRud

回答

1

默認情況下,Python中的函數返回None。只是要get_pos()返回tpos

def get_pos(): 
    with open("CONTCAR", "r") as finp: 
     for line in finp: 
      for _ in range(6): 
       sdata = finp.readline() 
       tpos.append(sdata.split()) 

    # print(tpos) 
    return tpos 

,然後像這樣:

Atom.pos = parsepos.get_pos() 
print(Atom.pos) 

希望這有助於!