python - 关于优化一些嵌套for循环的非常noob Python问题
问题描述
我对 Python很陌生,刚刚获得了一小段代码,可以将一些用户数据编译到一个文件中。但由于我只是在学习,我不只是希望它运行,而是要实际使用 Python 提供的功能。作为参考,这里是我认为可以做得更快的部分代码。
简而言之,我有一个文本文件中的用户名列表,以及每个用户在 4 个月内每天在 CSV 中的使用数据。
逻辑是
loop over each CSV:
loop over each line in that CSV:
loop over the list of usernames:
if the username matches, append the user data for that user
内部的两个 for 循环是我真正关注改进的地方,因为考虑到用户数量,这是存在一些瓶颈的地方。在下文中,username_list 是我从文本文件中读取的列表,而 read_csv 是从 csv 文件中读取的列表。工作代码如下:
#Initialise a dictionary of lists to store the final data and read the keys (which are the usernames)
main_data = {}
with open(".\\listofusernames.txt") as usernames:
username_list = usernames.read().splitlines()
for user in username_list:
main_data[user] = []
#Loop over the CSV files with usage data for each day for 3 months
for i in range(1,91):
csvdir = f".\\csvfiles\\usagedata_{i}.csv"
with open(csvdir, 'r') as daily_usage_csv:
read_csv = list(csv.reader(daily_usage_csv))
#Nested loops over the username list and CSV to get the data for the correct user
for user in username_list:
for line in read_csv:
#Username is stored in the first column of CSV so we do an if statement on index 0 of the line
if line[0] == user:
#Usage data is in the second and third column of the CSV, so we append index 1 and 2
main_data[user].append(line[1])
main_data[user].append(line[2])
break
我真正想要优化的地方是内部的两个 for 循环,位于电子邮件列表和 CSV 中的行之上。我希望使用 Python 的 maps() 函数而不是显式的 for 循环来做到这一点。问题是我正在迭代的对象没有索引我要附加的东西,所以我不确定如何实现它。
谁能在这里给出一些关于如何使循环更快的简单提示?
解决方案
你不需要两个 for 循环。您只需要一个,那就是遍历 csv 以获取使用数据。然后检查line[0]
ieuser
是否已经存在于字典中main_data
。然后插入到main_data
.
for line in read_csv:
if line[0] in main_data:
main_data[line[0]].append(line[1])
main_data[line[0]].append(line[2])
推荐阅读
- reactjs - React 功能组件状态变化不会触发子组件重新读取其 props
- php - 根据PHP更改所有页面上的链接
- swift - AppStore 查看崩溃日志
- cassandra - 我可以将计数器类型字段用作 C* 表的主键吗?
- r - 如何解决错误:无法在 RStudio 中分配大小为 70.7 Gb 的向量?
- python-3.x - ITM(爱尔兰横坐标)转换为谷歌地图 Python3 的 GPS
- embedded - 在 Eclipse IDE 上使用带有 MBED 库的矢量偏移表
- gremlin - 如何使用 Gremlin 查询获取特定标签的源顶点和目标顶点之间的所有传入中间顶点的列表?
- javascript - 尽管使用了等待,但异步函数返回待处理的承诺
- javascript - div 的 sessionStorage css 属性