0

我想在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 脚本中,类似于结构数组并相应地访问。

4

4 回答 4

1
import csv

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

print(lines)
于 2013-07-01T06:55:39.437 回答
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 ]

于 2013-07-01T07:17:16.357 回答
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]
        })
于 2013-07-01T06:53:59.580 回答
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.
于 2013-07-01T07:12:40.653 回答