【问题标题】:How to make the code run faster, possibly replacing the for loops in his code? (Python)如何使代码运行得更快,可能替换他代码中的 for 循环? (Python)
【发布时间】: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


【解决方案1】:

是的,有一种更简单的方法可以使用线性代数方法来实现这一点。使用numpy 时,尽量避免将numpy 数组转换回python 列表。这违背了目的。

本质上,您在这里所做的是一个简单的矩阵乘法。您所要做的就是重塑 numpy 数组以实现您想要的。

import numpy as np

list_shot = np.arange(0, 100, 50).reshape((2, 1))
list_lens = np.arange(10).reshape((1, 10))
print(list_shot)
print(list_lens)
print(np.matmul(list_shot, list_lens))

输出:

[[ 0]
 [50]]
[[0 1 2 3 4 5 6 7 8 9]]
[[  0   0   0   0   0   0   0   0   0   0]
 [  0  50 100 150 200 250 300 350 400 450]]

【讨论】:

  • 不幸的是,这个问题是在两个不同的地方同时提出的。如果您认为您的代码比其他代码更快,并且可以提供粗略的 CPU 时序,也欢迎您在此处添加答案:mattermodeling.stackexchange.com/q/8470/5
猜你喜欢
  • 2020-12-20
  • 1970-01-01
  • 2019-10-09
  • 2017-11-18
  • 1970-01-01
  • 2022-12-14
  • 2017-07-11
  • 2022-11-02
  • 2012-12-11
相关资源
最近更新 更多