【问题标题】:How to iterate through random or specific values in a range? in a non sequential way, in Python如何遍历一个范围内的随机或特定值?以非顺序方式,在 Python 中
【发布时间】:2021-11-02 09:02:25
【问题描述】:

Python 在 for 循环中遍历范围的方式是从 (0 到 n) 给定范围,它将首先对 0 执行操作,然后对 1、2... 执行操作,直到它在 n 中完成,完成 for环形。我对么? 我有一个工作代码需要针对速度进行优化,它看起来像这样:

Phi = np.arange(0.00005, 0.000101, 0.000001)
Strip_depth = 0.001
for angle in Phi:
    Neutral_axis_depth = np.arange(150, 160, 0.0001)
    for xn in Neutral_axis_depth:
        Sn = int(xn / Strip_depth) 
        x = [0]  # strip center coordinates
        for i in range(0, Sn - 1):
            x.append(x[i] + Strip_depth)
...
# and the a lot of calculations that will eventually result on C and T
...
        comparison_parameter = 0.1
        dif = T - C
        if comparison_parameter > dif > -comparison_parameter:
            # here I need to print the corresponding values of Phi, Xn , C, T and dif in a table
            # but that's another question...

我的问题是我需要高精度的结果,为此我必须修改 "strip_depth" 或 "Neutral_axis_depth" np.range step,这会导致更多的操作,需要更多的时间。 我认为与其按顺序执行 Xn 中的迭代,不如通过在范围内选择一个随机值并根据该值继续执行来节省时间,例如:

如果 dif 是 negative 我可以忽略从该点向前的范围值 如果 dif 是 positive 我可以忽略该点之前的范围值

并在 dif > comparison_parameter 时重复此操作。这种方式操作不做Sn次,只做几次。另一种选择是确定迭代的值,例如范围的 1/3、范围的 2/3,然后是“剩余范围”的 1/3 或类似的值。 在某种程度上,我正在通过这些步骤定义一个新范围。无论哪种方式,我都不知道该怎么做...在此先感谢您的帮助。

【问题讨论】:

    标签: python numpy iteration nonsequential


    【解决方案1】:

    我不完全遵循,但似乎range() 不是这个用例的最佳选择。如果您想根据需要调整选择的值,请使用while + 手动调整的自定义变量:

    i = 0 # initiate the custom variable 
    while i < Sn - 1: # instead of range()
    
        # under normal circumstances increase `i` in each loop by 1
        i += 1
    
        # if specific conditions are met, increase the value as needed
        if dif < 0:
            i += 50 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多