如何将一个字符串列表变成一个对象?

时间:2019-05-26 23:59:22

标签: python class object for-loop

从字面上看,这是我在python上的第二天,因此,如果涉及到诸如元类之类的复杂内容,请告诉我,以便在我有更多经验时可以再次使用。 我正在尝试在对象中转换字符串,我想我差不多了,所有内容都在代码部分中进行了详细说明。

# Call API
- name: Call API
  uri:
    url: myURL
    method: POST
  register: apiCheckResult

- name: Debug Auto tags
  debug:
    msg: "{{ item.name }}"
  loop: "{{ apiCheckResult.json['values'] }}"
  when: item.name == "myDemo"
  register: tagExists
mike carpenter miami
jon driver roma
erika student london

# here's my text file, is a list of strings

如果我也跑步


p = []

with open('people.txt', 'r') as text:
    for line in text:
        values = line.split(' ')
        p.append((values[0], values[1], values[2]))

#this converts each string in the text file in a list of strings with
# substrings becoming strings, all is put in a tuple named p

class person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

#this is my class, pretty self-explanatory
#now I can create objects like this:

person_number_0 = person(p[0][0], p[0][1], p[0][2])

#I can create objects using the tuple, but I don't want to do it manually
#for every different index, so I was thinking about a for-loop

n = 0
for line in p:
    obj = person(p[n][0], p[n][1], p[n][2])
    n = n + 1
#but I don't know how to create a new obj's name for every index


它给了我迈克(Mike),不应该是Erika吗,因为在循环结束时

print(obj.name)

还是不是?

如果事情太复杂,我会退缩的,请不要破坏我。谢谢大家的帮助或教训。

2 个答案:

答案 0 :(得分:2)

在定义类的同时,只需将文件读取为类似的内容即可:

with open('people.txt', 'r') as f:
    people = [person(*line.split()) for line in f]

现在您可以看到以下内容:

for p in people:
    print(p.name, p.job, p.location)

答案 1 :(得分:1)

代码:

# ignore this part it is the same as your code to read from the file
persons = [x.split() for x in """
    mike carpenter miami
    jon driver roma
    erika student london
""".split('\n')[1:-1]]


class Person:
    # this converts each string in the text file in a list of strings with
    # substrings becoming strings, all is put in a tuple named p
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def __str__(self):
        # this allows showing the class as a string (str)
        return "name: {}  job: {}  loc: {}".format(
            self.name, self.job, self.location)


for p in persons:
    print(Person(p[0], p[1], p[2]))

结果:

name: mike  job: carpenter  loc: miami
name: jon  job: driver  loc: roma
name: erika  job: student  loc: london