我正在尝试求出城市表中所有人口的平均值。我正在进行一个项目,下面是说明。我已经完成了第一步:
当我试图从“cities”表中获取“city_population“并将其除以列中的项时,我得到了一个错误。这是我的代码:
import sqlite3
import os
# Remove Database file if it exists:
os.remove('cities.db')
connection = sqlite3.connect("cities.db")
cursor = connection.cursor()
cursor.execute("create table if not exists cities(city_id INTEGER PRIMARY KEY NOT NULL, cities_name text, city_population integer)")
cities_list = [('Minneapolis', '425,336'),
('St. Paul', '307,193'),
('Dallas', '1,288,000'),
('Memphis', '628, 127'),
('San Francisco', '815,201'),
('Milwaukee', '569,330'),
('Denver', '711,463'),
('Phoenix', '1,625,000'),
('Chicago', '2,697,000'),
('New York', '8,468,000')]
cursor.executemany("INSERT OR IGNORE INTO cities VALUES (NULL, ?, ?)", cities_list)
# Print cities in alphabetical order
cursor.execute("select cities_name from cities")
result = sorted(cursor.fetchall())
print(result)
# Print average (NEED HELP HERE!)
cursor.execute("select city_population from cities")
result = cursor.fetchall()
average = sum(result) / len(result)
print(average)
connection.commit()
connection.close()
我希望显示总体的平均值,但我得到了一个错误。我该如何修复它?
1条答案
按热度按时间6ju8rftf1#
您的源人口数字包含逗号,您需要删除这些逗号。
数据库返回了一个元组,它本身不能使用sum()函数。你可以用很多方法来解决这个问题,这对我来说很有效:
来源:https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
以后,请提供错误消息。