【发布时间】:2022-01-04 19:23:05
【问题描述】:
import numpy as np
list_shot = list(np.arange(0, 100, 50))
list_lens = list(np.arange(10))
list_total = []
for shot in list_shot:
print("-", shot)
list_out = []
for lens in list_lens:
val = shot * lens
list_out.append(val)
print(list_out)
list_total.append(list_out)
基本上,上面的代码只是下面这段代码的简单表示,需要对其进行优化以使其运行得更快。
CN_list_shot = []
counter = 0
for shot in bec[1:1000:500]: ### reads from time snapshots
CN_list = []
for length in length_list: ### all the lenghts for the same snapshot
i = neighbor_list("i", shot, {('Ge', 'Ge'): length}, self_interaction= False)
coord = np.bincount(i)
CN_list.append(np.sum(coord) / np.count_nonzero(coord))
print("CN_list: ", CN_list) ### value added to the list for the snapshot
CN_list_shot.append(CN_List) ### the list added for each snapshots
【问题讨论】:
-
你想用什么替换 for 循环?
-
@mkrieger1 这正是我正在努力解决的问题。你有什么建议?
-
如果您的代码有效,但您只想提高效率,那么Code Review 可能更合适(假设您通过一些示例输入和输出以及对问题的描述来充实细节)
-
内部 for 似乎是调用 map 的好候选
-
已经相当快了。为什么要让它更快?您是否在两个更大的列表上运行此代码?如果有,请附上。
标签: python python-3.x list performance for-loop