Python - "Struct arrays"
I'd like to have a struct for every line I find in a text file. (So yeah, basically I want to define my struct, then count lines, and fill up my structs.)
In C++, C# it's fine. But I'm always开发者_JAVA技巧 lost in Python.
My structs would look like:
struct[0].name = "foo"
struct[0].place = "Shop"
struct[1].name = "bar"
struct[1].place = "Home"
And so on.
(Sorry for the lame question, hope other newbies (like me) will find it useful.)Of course, feel free to edit the question (title) to reflect the real thing.
You want to create a class which contains name
and place
fields.
class Baz():
"Stores name and place pairs"
def __init__(self, name, place):
self.name = name
self.place = place
Then you'd use a list of instances of that class.
my_foos = []
my_foos.append(Baz("foo", "Shop"))
my_foos.append(Baz("bar", "Home"))
See also: classes (from the Python tutorial).
That's what named tuples are for.
http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields
How about a list of dicts?
mydictlist = [{"name":"foo", "place":"Shop"},
{"name":"bar", "place":"Home"}]
Then you can do
>>> mydictlist[0]["name"]
'foo'
>>> mydictlist[1]["place"]
'Home'
and so on...
Using your sample file:
mydictlist = []
with open("test.txt") as f:
for line in f:
entries = line.strip().split(" ", 5) # split along spaces max. 5 times
mydictlist.append({"name": entries[0],
"time1": entries[1],
"time2": entries[2],
"etc": entries[5]})
gives you:
[{'etc': 'Vizfoldrajz EA eloadas 1', 'name': 'Hetfo', 'time2': '10:00', 'time1': '8:00'},
{'etc': 'Termeszetfoldrajzi szintezis EA eloadas 1', 'name': 'Hetfo', 'time2': '14:00', 'time1': '12:00'},
{'etc': 'Scriptnyelvek eloadas 1', 'name': 'Hetfo', 'time2': '16:00', 'time1': '14:00'}
...]
IIt depends of what you have as data.
If all that you want is to store names and places as string, I would suggest:
A list of namedtuples [(name="foo", place="Shop"), (name="bar", place="Home")]
For almost all cases, a Python list is analogous to a C array. Python has an array
module, but that is a thin wrapper around actual C arrays, so I wouldn't use that unless you need to expose something to/from C.
Also, a struct can easily be represented as an object. Something like:
class Data(object):
def __init__(self, name, place):
self.name = name
self.place = place
Then you want to loop through the file, line by line, and populate:
my_list = []
with open("myfile.txt") as f:
for line in f.readlines():
# line is each line in the file
# let's pretend our file structure is "NAME PLACE"
data = line.split() # data[0] = name, data[1] = place
my_list.append(Data(data[0], data[1]))
# my_list now contains objects of class Data, which has members name and place
That should be enough of a starting point to get you moving and help you understand how to do basic file/class/list operations.
You could use a dict or make a small class.
>>> s = [{'name': 'foo', 'place': 'shop'}, {'name': 'bar', 'place': 'home'}]
>>> s[0]['name']
'foo'
Also, I would recommend not naming it 'struct' in python since that is a python module.
class Struct:
def __init__(self, name, place):
self.name = name
self.place = place
structs = []
structs.append(Struct("foo","bar"))
structs.append(Struct("other_foo","other_bar"))
Don't see why to take so much pain
class your_struct():
def __init__(self, value, string):
self.num = value
self.string = string
C = [[ your_struct(0,'priyank') for j in range(len(n)) ] for i in
range(len(n)) ]
# for 2-D Matrix
C = [ your_struct(0,'priyank') for j in range(len(n)) ] // for 1-D array
精彩评论