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.
-
6If you continue to think in C++ or C#, you'll always be lost in Python. If you want to stop being lost in Python, you have to stop using C++ and C# terminology. It's hard to do, but it's the only way to get un-lost. We can't edit the title to reflect your understanding. You have to expand your understanding and then fix the title. You might want to read docs.python.org/dev/library/stdtypes.html again.S.Lott– S.Lott2011年04月28日 20:35:32 +00:00Commented Apr 28, 2011 at 20:35
-
1wow, I read all the comments and answers below, and I don't think any ot them actually answered the question as I understood it. How to make an indexable array of collections?jrive– jrive2021年03月03日 15:00:09 +00:00Commented Mar 3, 2021 at 15:00
9 Answers 9
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).
1 Comment
That's what named tuples are for.
12 Comments
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'}
...]
3 Comments
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")]
1 Comment
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.
Comments
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"))
Comments
You could use a dict or make a small class.
Comments
>>> 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.
Comments
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