2017-08-28 68 views
1

我有對應於另一個字母字母列表的文件:以文件格式化列表,列出蟒蛇

A['B', 'D'] 
B['A', 'E'] 
C[] 
D['A', 'G'] 
E['B', 'H'] 
F[] 
G['D'] 
H['E'] 

我需要這些列表導入到其相應的字母,以希望有看變量像這樣:

vertexA = ['B', 'D'] 
vertexB = ['A', 'E'] 
vertexC = [] 
vertexD = ['A', 'G'] 
vertexE = ['B', 'H'] 
vertexF = [] 
vertexG = ['D'] 
vertexH = ['E'] 

什麼是最好的方法來做到這一點?我試圖尋找答案,但這樣做卻不吉利。謝謝你的幫助。

+0

是吧'txt'文件還是什麼? – sKwa

+0

是的,我在一個名爲out.txt的文件中有這個信息 – wyskoj

+2

不,變量在這裏是錯誤的方法。你需要使用數據結構,比如'list'或'dict'。 –

回答

0

文件A.TXT:

A['B', 'D'] 
B['A', 'E'] 
C[] 
D['A', 'G'] 
E['B', 'H'] 
F[] 
G['D'] 
H['E'] 

代碼:

with open('A.txt','r') as file: 
    file=file.read().splitlines() 
    listy=[[elem[0],elem[1:].strip('[').strip(']').replace("'",'').replace(' ','').split(',')] for elem in file] 

這使得嵌​​套列表,但基督教Dean說,是一種更好的方式去。

結果:

[['A', ['B', 'D']], ['B', ['A', 'E']], ['C', ['']], ['D', ['A', 'G']], ['E', ['B', 'H']], ['F', ['']], ['G', ['D']], ['H', ['E']]] 
1

構建字典很可能是最好的。字母表中的每個字母都是一個關鍵字,然後該值將成爲關聯字母的列表。這裏有一個概念證明(未測試):

from string import string.ascii_uppercase 

vertices = {} 

# instantiate dict with uppercase letters of alphabet 
for c in ascii_uppercase: 
    vertices[c] = [] 

# iterate over file and populate dict 
with open("out.txt", "rb") as f: 
    for i, line in enumerate(f): 
     if line[0].upper() not in ascii_uppercase: 
      # you probably want to do some additional error checking 
      print("Error on line {}: {}".format(i, line)) 
     else: # valid uppercase letter at beginning of line 
      list_open = line.index('[') 
      list_close = line.rindex(']') + 1 # one past end 
      # probably would want to validate record is in correct format before getting here 
      # translate hack to remove unwanted chars 
      row_values = line[list_open:list_close].translate(None, "[] '").split(',') 
      # do some validation for cases where row_values is empty 
      vertices[line[0].upper()].extend([e for e in row_values if e.strip() != '']) 

使用那麼它會很容易:

for v in vertices['B']: 
    # do something with v 
1

您可以嘗試使用字典而不是變量,而且我認爲它可以更容易,以及以從你的文本文件填充你的數據。

vertex = {} 
vertex['A'] = ['B', 'D'] 
vertex['A'] 
>>> ['B', 'D'] 
1

當你讀你的輸入文件,輸入應該是這樣的:

string='A["B","C"]' 

所以,我們知道的第一個字母是列表的名稱。

import ast 
your_list=ast.literal_eval(string[1:]) 

your_list: 
['B', 'C'] 

可以照顧循環,閱讀文件和字符串操作適當命名...