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

ここで提案されたことに加えて、Python が (C ではなく) OOP を実行できるという事実を利用したい場合があるため、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 に答える
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 に答える
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 に答える
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 に答える