29

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.

2
  • 6
    If 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. Commented Apr 28, 2011 at 20:35
  • 1
    wow, 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? Commented Mar 3, 2021 at 15:00

9 Answers 9

24

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is the way. No idea why this is not the accepted answer.
14

That's what named tuples are for.

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

12 Comments

@S. Lott, why not just dicts which are not limited to more recent python versions.
@kanaka: ['foo'] is harder to type than .foo and adds no value (assuming the names are fixed. If the names are dynamic, you should propably use dicts, yeah). And 2.6 is hardly recent, you should be using it anyway unless you're forced not to by the production enviroment.
@kanaka: It's easier to upgrade than it is to fool around with an inappropriate data structure.
@S. Lott, there's nothing inappropriate about using python dicts for structured data like that. In fact I would argue that named tuples are inappropriate since they are a more obscure python type, they aren't native until 2.7 (whereas dicts have been there since the beginning) and the question does not imply that ordering is required for the named elements (which is where named tuples would be appropriate). And either you don't upgrade python very often, or you've done it so much you've forgotten how involved it is for non-admin people (the problem is the versioned modules, not python itself).
@kanaka: Given a choice between named tuples and dicts, I found named tuples to be less obscure, correct. That was why I posted the answer I posted. The dictionary is slightly more obscure. Hence my answer. You're correct. I'm sorry that I don't understand which version is appropriate for answering the question. I'm sorry I assumed most folks have a version with namedtuples. I apologize for violating your expectations for answering in way that's compatible with pre-2.6 Python. I apologize. I will not change my answer, but I apologize for offending you.
|
8

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

And how can I automate this? Like ... I'm reading from the file, and then how do I create them? Like... How do I refer to them? (If it's a new question, sorry. AND thanks for the (very) fast answer.)
What does your file look like?
Here it is: pastebin.com/EwrL5Mbs (Guess some other people will notice the text file.. it's a task for a class.)
3

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

unnecessary for this and not compatible with python 2.6 and older.
3

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

1
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

0

You could use a dict or make a small class.

Comments

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

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.