来自for循环的唯一对象标识符

时间:2015-01-27 16:04:10

标签: python

我正在尝试从CSV文件中读取的每一行创建唯一对象。 问题是为每个对象创建一个唯一的ID。我想先创建一个包含所有对象的列表,但我不知道CSV文件中包含了多少项。如何为每个不随机的对象生成唯一ID?我知道我不能使用字符串来定义对象,但我不知道如何解决这个问题。

class House():
    def __init__(self,x,y,number,price):
        self.x = x
        self.y = y
        self.number = number
        self.price = price

    def __str__(self):
        result = " Latitude: {} '\n' Longitude: {} '\n' Price: {} '\n' House Number: {}".format(self.x,self.y,self.price,self.number)
        return result

def acquire_data(): 
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    for row in reader:
        main= "House{}".format(int(row[2]))
        main = House(row[0],row[1],row[2],row[3])
        print row

2 个答案:

答案 0 :(得分:1)

经过长时间讨论后编辑

(...)

def acquire_data(): 
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    houses = {}
    for row in reader:
        housenumber = int(row[2])
        house = House(row[0],row[1],row[2],row[3])
        houses[housenumber] = house

    print houses[5]   # print house number 5
    print houses[5].price   # print price of house number 5

答案 1 :(得分:0)

class House():
    def __init__(self,x,y,number,price,id):
        self.x = x
        self.y = y
        self.number = number
        self.price = price
        self.id = id

    def __str__(self):
        result = " Latitude: {} '\n' Longitude: {} '\n' Price: {} '\n' House Number: {}".format(self.x,self.y,self.price,self.number)
        return result

def acquire_data(): 
    with open('example.csv', 'rb') as f:
    reader = csv.reader(f)
    headers = reader.next()
    houses = {}
    for row in reader:
        #main= "House{}".format(int(row[2]))
        tmp = House(row[0],row[1],row[2],row[3],id)
        houses[id] = tmp
        id += 1
        print row
    return houses