开发者

How to Access a List within a List in linear Time and Create Indeterminate Numbers of Objects

In Python, I'm currently working on a project. I am storing lines from a file as a list. In these lines, I want to delimit the strings by spaces and store the individual words from the line in an object.

Each line contains three "words" spaced apart. I want to store each word as an element in a class object. Since I do not know how many lines the user may have in the input file, these objects will be created in an indeterminate amount.

When I run through the list of lines and "split" them, I get a list within a list. I do not know what to do with the data in that form (without using a for-loop within a for-loop), I'm stuck here.

I already have the object class created with three fields and methods to access those fields. However, I do not know how to access the "list within a list" (in linear time) and delimit the words and easily and quickly create a new object with the words as the parameters.

If anyone could give me advice 开发者_JAVA技巧on where to go from here, I would appreciate it. Thank you.


class MyClass(object):
    def __init__(self, word1, word2, word3):
        # your initialisation code here

for line in list_of_lines:
    words = line.split()
    assert len(words) == 3
    an_object = MyClass(*words)
    do_something_with(an_object)

Update in response to comment:

To get a list of MyClass objects, one for each line in your input file:

with open("my_input_file.txt") as f:
    the_list = [MyClass(*line.split()) for line in f]


Why split them before use? Why not split the line when you need it?

Some pseudo codeish

for each line in list
    items = line split
    object(items)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜