我正在尝试使用构造函数方法使用来自.csv的数据在Python中填充城市列表。但是,我不了解如何自动化该过程。我可以一次实例化一个城市,如下所示,但是有30多个行,并且真的希望不要手动进行。下面是我正在使用的代码示例,以及how the data is stored in Python。
##Step 1. Open and read CityPop.csv
file = "CityPop.csv"
try:
csv = open(file, 'r')
##Step 1A. Deal with bad inputs
except:
print("Could not open" + file)
sys.exit()
##Step 3. Create "Cities" list
Cities = []
##Step 2. Create "City" class
class City:
##Step 4. Use __init__ method to assign attribute values
def __init__(self, lat, lon, name, yr1970):
self.lat = lat
self.lon = lon
self.name = name
self.yr1970 = yr1970
city_1=City(35.6832085, 139.8089447, 'Tokyo', 23.3)
city_2=City(28.6082802, 77.2008133, 'New Delhi', 3.53)
Cities.append(city_1)
Cities.append(city_2)
有没有更有效的方法可以做到这一点?谢谢!