7年来每月捕获数据的最佳数据结构-列表阵列



我是python的新手。很久以前是一名C开发人员。我正在学习Python,这是一个在封锁期间进行自我教育的个人项目。

我的项目是阅读一个论坛网站,每月在一个特定的论坛上捕捉帖子。

我已经取得了一些进展,可以扫描网站,提取帖子数量并分配到特定的月份。我还没有确定年份。我只需要帮助正确的数据结构来表示所有年份的数据。

表示固定范围的10年月度数据的最佳方式是什么?

我的偏好是尽可能地坚持内置功能。

一个建议是使用JSON,尽管我一直盯着JSON文档看,并感到困惑。

我搜索python列表数组——答案让我感到困惑。

year = {
1: {"name": "Jan", "count": 0},
2: {"name": "Feb", "count": 0},
3: {"name": "Mar", "count": 0},
4: {"name": "Apr", "count": 0},
5: {"name": "May", "count": 0},
6: {"name": "Jun", "count": 0},
7: {"name": "Jul", "count": 0},
8: {"name": "Aug", "count": 0},
9: {"name": "Sep", "count": 0},
10: {"name": "Oct", "count": 0},
11: {"name": "Nov", "count": 0},
12: {"name": "Dec", "count": 0}
}
# Testing
for month, data in year.items():
print(year[month]["name"], year[month]["count"])
year[month]["count"] = random.randrange(10)
print(year)

对于固定的年份,并且尽可能使用python本机,请使用列表列表,例如a = [[1,2],[3,4]]

nb_of_months_in_a_year = 12
nb_of_years = 10
counts = [[0 for i in range(nb_of_months_in_a_year)] for j in range(nb_of_years)]
# counts is now a list of lists, and can be viewed as a matrix with 10 rows and 12 colums. 1 row per year, 1 column per month
for year in counts:
print(year)
# increment 4th year (counting from 0), februari (counting from 0):
counts[3][1] += 1
print(counts)
# get count in februari in all years:
total = 0
for year in counts:
total += year[1]
print(total) # yields 1

最新更新