我试图使用构造函数方法,使用.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)
我有没有更有效的方法来完成这个任务?谢谢
目前没有回答
相关问题 更多 >
编程相关推荐