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.
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")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With