- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个字典“更新”算法,我怀疑它不是最有效的方法。当我运行程序并不断向现有词典添加新词典时,性能会随着时间的推移而显着下降。我想找到一种更高效的方法。
我有一个循环,每次迭代都会处理一个文件,并产生“字典列表的字典”。每个主字典键都有一个列表值,其中的项目本身就是字典,其中可以有多个。在此示例中,属于 B 的列表中有两个字典。我可能会处理第一个文件并得到这个结果:
{'A': [{'filename': 6311, 'id': 6634, 'num_transactions': 4969, 'total': 7808}],
'B': [{'filename': 6311, 'id': 3578, 'type': 8268, 'diameter': 2281, 'width': 4617},
{'filename': 6311, 'id': 2289, 'type': 1553, 'diameter': 4104, 'width': 8725}]}
然后我可能会处理另一个文件并得到这个:
{'C': [{'filename': 7775, 'id': 177, 'count': 6139, 'needed': 7905}],
'B': [{'filename': 7775, 'id': 7540, 'type': 9854, 'diameter': 3729, 'width': 9145},
{'filename': 7775, 'id': 27, 'type': 2380, 'diameter': 7209, 'width': 6023}]}
然后,我将这些字典组合成一个主字典,在其中根据它们的键值不断组合列表。上述两个字典的组合将导致(这里的顺序是任意的,但为了可读性而排序):
{'A': [{'filename': 6311, 'id': 6634, 'num_transactions': 4969, 'total': 7808}],
'B': [{'filename': 6311, 'id': 3578, 'type': 8268, 'diameter': 2281, 'width': 4617},
{'filename': 6311, 'id': 2289, 'type': 1553, 'diameter': 4104, 'width': 8725},
{'filename': 7775, 'id': 7540, 'type': 9854, 'diameter': 3729, 'width': 9145},
{'filename': 7775, 'id': 27, 'type': 2380, 'diameter': 7209, 'width': 6023}],
'C': [{'filename': 7775, 'id': 177, 'count': 6139, 'needed': 7905}]}
请注意,我必须有一个最终的 master_dict,其中包含我所有词典的组合数据,这是不容协商的。
下面是一个完整的程序,用于生成随机 cur_dicts
并将其结果不断添加到 master_dict
中。函数 add_to_master_dict()
代表我的更新算法。
import random
import timeit
import matplotlib.pyplot as plt
random.seed(0)
a_keys = ['id', 'num_transactions', 'total']
b_keys = ['id', 'type', 'diameter', 'width']
c_keys = ['id', 'count', 'needed']
key_dict = {'A':a_keys, 'B':b_keys, 'C':c_keys}
def generate_cur_dict(key_dict):
cur_dict = {}
filename_int = random.randint(0, 10000)
for main in random.sample(key_dict.keys(),
random.randint(1, len(key_dict.keys()))):
cur_dict[main] = []
num_rows = random.choice([1, 1, random.randint(1, 3)])
for _ in range(num_rows):
temp_dict = {}
temp_dict['filename'] = filename_int
for k in key_dict[main]:
temp_dict[k] = random.randint(0, 10000)
cur_dict[main].append(temp_dict)
return cur_dict
# Hacky use of variable scope by assuming existence of cur/master_dict,
# but easiest way to pass to timeit
def add_to_master_dict():
if not master_dict: # master_dict is empty
master_dict.update(cur_dict)
else:
for k in cur_dict.keys():
if k in master_dict:
# In case of None value rather than a list
if cur_dict[k] is None:
continue
else:
# Combine the two lists based on key
master_dict[k] = master_dict[k] + cur_dict[k]
else:
# If key not in master dict, just add the cur_dict value to the
# master_dict
master_dict[k] = cur_dict[k]
master_dict = {}
times = []
for i in range(50001):
cur_dict = generate_cur_dict(key_dict)
times.append(timeit.timeit(add_to_master_dict, number=1))
# Easy visual way to see how much it slows down over time
if i % 1000 == 0:
print(i)
plt.figure(figsize=(10, 6))
plt.plot(times)
我知道这不是使用 timeit 的最优雅的方式 - 我没有取执行的平均值,因此存在很多变化 - 但我只是想演示这个概念。应该清楚的是,如果您运行任意大量迭代,add_to_master_dict()
就会陷入相当大的困境,因此我可能会在此处查看指数增长的更新。
对于如何以(希望)实现线性时间的方式执行更新操作,有什么建议吗?我已经能够找到在简单情况下表现良好的字典/列表更新算法,但对于我的列表字典用例却没有找到。
最佳答案
这一行
master_dict[k] = master_dict[k] + cur_dict[k]
每次执行时都会创建一个新列表。扩展现有列表
master_dict[k] += cur_dict[k]
速度要快得多。在我的机器上,执行时间从 1 分 46.857 秒变为 8.027 秒。
我不是专家,但我怀疑这两个版本的代码都在大致*线性时间内运行。然而,在原始代码中,每次执行该行都必须构造一个长度为 n + k 的新列表,而在改进版本中,现有列表扩展了 k 个元素,这需要更少的内存分配和对象构造。
* 扩展列表以摊销线性时间运行 - 请参阅 https://wiki.python.org/moin/TimeComplexity
关于Python-将许多列表字典添加到持久主字典时的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59536384/
我是Hibernate的新手。当我保存特定实体时,它将从现有实体中重写数据。 我将ID用作自动生成,如下所示: @Id @GeneratedValue(strategy=GenerationType.
我正在尝试以连续模式使用CouchDB更改通知API,所以我想发送此消息 _changes?feed = continuous?include_docs = true作为GET请求到达我的CouchD
我有 XMPP 服务器(openfire)和一堆客户端(spark),分为几个组(部门)。我正在寻找能够将它们留在 session 室中的能力。我的意思是 Skype 具有的类似功能;当用户关闭带有群
我发布这个问题是为了看看我是否正确理解 Azure Functions 中的并行性,特别是 Durable Functions。 最近使用 az cli 在 Azure Functions 中添加了设
我在 Dev Env 上有一个 AKS 集群,上面运行着一些容器。我还启用了 Azure Log Analytics。但我可以看到正在运行的当前容器的日志,而不是已被终止或停止的旧容器的日志。 我想知
在 Akka 中,当一个 actor 在处理消息时死亡(在 onReceive(...) { ... } 内),该消息就会丢失。有没有办法保证无损?有一种配置 Akka 在将消息发送到 onRecei
我试图让 selectOneMany 取得有限的成功。 我有以下数据库模型 User email Text verkey Text Maybe verified Bool password T
我需要使用持久性(Yesod)从键列表中获取实体列表 假设我有一个 Model 及其相应的 ModelId。我身边有: keys :: [ModelId] 我需要得到 models :: [Model
我有一个使用 GWT、请求工厂和地点/Activity 构建的网络应用程序。我很好奇我使用的历史 token 是否持久。该任务基本上就是让 URL 定义我的网络应用程序的确切位置(读作“文件/文件夹结
我正在寻找一种 jQuery 方法来在刷新页面时使页面元素持久保留在用户屏幕上。当我刷新页面并且丢失 jQuery 页面中的内容时,它会发生变化。 我需要页面持久。如何刷新页面并保持元素不刷新(持久)
当我尝试使用 gcc 编译带有 -fopenmp 标志的 C 代码时,我已经持续收到此错误超过 6 小时了。 错误:控制谓词无效 for ( int i = 0; i #include #ifde
我有带有验证注释的实体,例如@NotNull。我不知道如何防止容器管理的事务在批量持久操作中出现 ConstraintViolationException 的情况下回滚,例如: public void
这是我的代码: http://jsfiddle.net/KCb5z/8/embedded/result/ http://jsfiddle.net/KCb5z/8/ $(function () {
我正在与服务器通信,理想情况下,我希望输入流和输出流始终处于运行状态。我收到未经请求的响应,因此我必须始终准备好接收输入流上的数据。 在我进一步深入之前,我应该说我建立的任何连接都必须能够支持 SSL
我正在寻找一种正确扩展 Azure Functions 的方法,但遇到了问题。 我有一组 IoT 设备,通过 HTTP 向 Azure 发送数据(为此,有一组自动扩展的 Azure Functions
1.临时态(瞬时态) 不存在于session中,也不存在于数据库中的数据,被称为临时态。 比如:刚刚使用new关键字创建出的对象。 2.持久态 存在于session中,事务还未提交,提交之后
我在 Kohana v2 中使用数据库 session 驱动程序。为了使 session 持久化,Kohana 创建了一个 token cookie。这个 cookie 使用了我想的 cookie 配
有谁知道是否有办法使用 PyWinrm 打开一个持久的 PowerShell session ,该 session 保持状态并且可以多次调用?我正在尝试执行以下操作: #!/bin/python im
在运行的Elasticsearch集群中,配置文件中的index.number_of_replicas设置为1。 我可以通过运行以下命令在运行的集群上将其更新为2 # curl -XPUT "http
我在“这么长的帖子必须意味着大量的代码和配置”部分下一对一地使用指南代码。 http://blog.springsource.com/2006/08/07/using-jpa-in-spring-wi
我是一名优秀的程序员,十分优秀!