在Golang中访问for循环之外的变量

时间:2019-06-18 16:03:09

标签: csv for-loop go scope func

我正在尝试读取CSV文件以将值存储在变量中。但是,我无法在for循环

之外访问变量。
class People:
    def __init__(self, name, age, pets_owned):
        self.name=name
        self.age=age
        self.pets_owned=pets_owned

P1=People("John",16, 1)
P2=People("Alex",10, 4)
P3=People("Anna", 20, 3)


People_List=[P1, P2, P3]
People_Age=[P1.age, P2.age, P3.age]

class Animal:
    def __init__(self, name, age, owner):
        self.name=name
        self.age=age
        self.owner=owner

    def find(self):
        people_with_less_than_3 = filter(lambda x: x.pets_owned<3, People_List) # filter the list to only include people that have less than 3 pets
        try:
            person_with_closest_age = min(people_with_less_than_3, key=lambda x: abs(x.age - self.age)) # change this to return a person as well
        except:
            # do something if no person with < 3 pets
        self.owner = person_with_closest_age.name
        print(self.owner)


A1=Animal("Snoopy",7,"not_owned_yet")


A1.find()

1 个答案:

答案 0 :(得分:0)

reader.Read()返回io.EOF时,循环中断。消耗您的输入时就会发生这种情况。

同时(返回io.EOF时,返回的记录将为nilReader.Read()

  

如果没有要读取的数据,读取将返回n.io.EOF

因此,您将nil分配给record变量,循环中断,并检查record变量。

如果您要保留最后一条记录,请将其存储在单独的变量中,并且不要用最后的nil条记录“覆盖”

var lastRecord []string
for {
    record, err = reader.Read()
    // Stop at EOF.
    if err == io.EOF {
        break
    }
    lastRecord = record
    fmt.Printf("%v", record) // works fine
    fmt.Printf("%v\n", record[0]) // works fine too
}
fmt.Printf("%v\n", lastRecord) // this will be the last non-nil record