Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 680
Apache Avatar asked Apr 28 '11 20:04

Apache


4 Answers

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).

like image 134
Matt Ball Avatar answered Nov 03 '22 07:11

Matt Ball


That's what named tuples are for.

http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

like image 22
S.Lott Avatar answered Nov 03 '22 07:11

S.Lott


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'}
 ...]
like image 29
Tim Pietzcker Avatar answered Nov 03 '22 05:11

Tim Pietzcker


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")]

like image 42
Xavier V. Avatar answered Nov 03 '22 07:11

Xavier V.