简体   繁体   English

Python:从.txt文件填充对象列表

[英]Python: filling a List of objects from a .txt file

For starters I've programmed in C++ for the past year and a half, and this is the first time I'm using Python. 对于初学者,在过去的一年半中,我已经使用C ++编程,这是我第一次使用Python。

The objects have two int attributes, say i_ and j_. 这些对象具有两个int属性,例如i_和j_。

The text file is as follows: 文本文件如下:

1,0
2,0
3,1
4,0
...

What I want to do is have the list filled with objects with correct attributes. 我想做的是让列表填充具有正确属性的对象。 For example, 例如,

print(myList[2].i_, myList[2].j_, end = ' ')

would return 会回来

3 1

Here's my attempt after reading a little online. 这是我在网上阅读一些内容后的尝试。

class myClass:
    def __init__(self, i, j):
        self.i_ = i
        self.j_ = j   

with open("myFile.txt") as f:

    myList = [list(map(int, line.strip().split(','))) for line in f]

    for line in f:
        i = 0
        while (i < 28):
            myList.append(myClass(line.split(","), line.split(",")))
            i +=1

But it doesn't work obviously. 但这显然不起作用。

Thanks in advance! 提前致谢!

Since you're working with a CSV file you might want to use the csv module. 由于您使用的是CSV文件,因此您可能要使用csv模块。 First you would pass the file object to the csv.reader function and it will return an iterable of rows from the file. 首先,您将文件对象传递给csv.reader函数,它将返回文件中可迭代的行。 From there you can cast it to a list and slice it to the 29 rows you are required to have. 从那里,您可以将其转换为列表,并将其切成需要的29行。 Finally, you can iterate over the rows (eg [1,0]) and simply unpack them in the class constructor. 最后,您可以遍历行(例如[1,0]),然后只需将它们解压缩到类构造函数中即可。

class MyClass:
    def __init__(self, i, j):
        self.i = int(i)
        self.j = int(j)

    def __repr__(self):
        return f"MyClass(i={self.i}, j={self.j})"

with open('test.txt') as f:
    rows = [r.strip().split(',') for r in f.readlines()[:29]]
    my_list = [MyClass(*row) for row in rows]

for obj in my_list:
    print(obj.i, obj.j)

print(len(my_list))

I'm not sure what you're trying to do with myList = [list(map(int, line.strip().split(','))) for line in f] . 我不确定您要使用myList = [list(map(int, line.strip().split(','))) for line in f] This will give you a list of lists with those pairs converted to ints. 这将为您提供将这些对转换为int的列表的列表。 But you really want objects from those numbers. 但是您真的想要这些数字中的对象。 So let's do that directly as we iterate through the lines in the file and do away with the next while loop: 因此,当我们遍历文件中的各行并取消下一个while循环时,让我们直接执行此操作:

my_list = []
with open("myFile.txt") as f:
    for line in f:
        nums = [int(i) for i in line.strip().split(',') if i]
        if len(nums) >= 2:
            my_list.append(myClass(nums[0], nums[1]))

I not sure you really what to stick with this format 我不确定您到底要坚持这种格式

print(myList[2].i_, myList[2].j_, end = ' ')

My solution is quite manual coded and i am using dictionary to store i and j 我的解决方案是相当手动编码的,并且我使用字典来存储i和j

result = {'i':[],
  'j':[]}

and below is my code 下面是我的代码

result = {'i':[],
      'j':[]}

with open('a.txt', 'r') as myfile:
    data=myfile.read().replace('\n', ',')
print(data)

a = data.split(",")
print (a)

b = [x for x in a if x]
print(b)

for i in range( 0, len(b)):
    if i % 2 == 0:
        result['i'].append(b[i])
    else:
        result['j'].append(b[i])


print(result['i'])
print(result['j'])
print(str(result['i'][2])+","+ str(result['j'][2]))

The result: 3,1 结果:3,1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM