2013-07-01 63 views
0

我想要實現在python以下, 用C讀取數據實現結構在python(類似於C)的陣列,它像下面,有一個結構通過從文件

struct xyz { 
char name[50]; 
char type[50]; 
char link[50]; 
char level[50]; 
}XYZ; 

而我已經建立此結構的xyz的陣列如下:

XYZ array[] = 
{ {"Mac", "char", "list","one"}, 
    {"John", "char", "list","three"}, 
    ... 
    ... 
}; 

和由陣列[0],陣列[1]等 訪問這些在Python腳本,假設我列出在文本文件中,這些陣列元件如下所示,例如file.txt的

Mac, char, list, one 
John, char, list, three 
... 
... 

現在我要讀的file.txt的,並將它們存儲到我的相似,因此結構和訪問數組python腳本。

回答

0

您的語法有點偏差。

這將創建4個值的數組的數組:

XYZ = [ 
    ["Mac", "char", "list","one"], 
    ["John", "char", "list","three"], 
    ... 
    ... 
] 

這將創建對象的數組具有4個字段:

XYZ = [ 
    {"name": "Mac", "type": "char", "link": "list", "level": "one"}, 
    {"name": "John", "type": "char", "link": "list", "level": "three"}, 
    ... 
    ... 
] 

爲了從文件中讀取該數據到像#結構2:

import csv 

XYZ = [] 
with open("data.csv") as csv_data: 
    entries = csv.reader(csv_data, delimiter=",") 
    # This can be done with list comprehension, but will be difficult to read 
    for entry in entries: 
     XYZ.append({ 
      "name": entry[0], 
      "type": entry[1], 
      "link": entry[2], 
      "level": entry[3] 
     }) 
+0

他的語法是C,而不是Python,這就是爲什麼它看起來像Python一樣奇怪。 :D – torek

+0

非常感謝,這與我正在嘗試做的類似,但我將如何獲得相應的價值?這意味着如果我在XYZ搜索字符串'Mac',並且如果找到,那麼我需要相應的類型,鏈接和級別。 –

+0

如果您需要搜索「name = Mac」: '[entry for entry在XYZ中如果entry.name ==「Mac」]'會返回你相應條目的列表。 – mishik

1
import csv 

with open('somefile.txt') as f: 
    reader = csv.reader(f, delimiter=',') 
    lines = list(reader) 

print(lines) 
0
import csv 

from collections import namedtuple 
XYZ = namedtuple('xyz', ['name', 'type', 'link', 'level']) 

with open('somefile.txt') as f: 
    reader = csv.reader(f, delimiter=',') 
    lines = [XYZ(*line) for line in reader] 

for item in lines: 
    print(item.name) 
    print(item.type) 
    #etc. 
+0

謝謝,我試過了但它會得到錯誤:'lines = [XYZ(線)在線閱讀器] TypeError:__new __()只需要5個參數(給出2)' –

+0

@Jaiswal,應該是'lines = [XYZ(* line)對於讀者來說]' –

1

在這裏建議什麼上面,你可能要採取的事實,Python可以做OOP(相對於C)的優勢,所以加入到Burjan的答案,我會做這樣的事情:

class xyz(): 
def __init__(self, name, type): 
    self.name = name 
    self.type = type 
    // etc 

然後調用類似result = [ xyz(*line) for line in lines ]