我試圖找到一種簡單的方法來執行下面的“代碼 1”,但我不知道為什么結果不一樣。我的老師創建了一個有 6 個 elif 的代碼,我認為這不是實用的方法。我嘗試在 for, for a 中使用 for range (0,7),因為代碼 1 有 7 if,0 到 7,但沒有用,正如您在列印 4 中看到的那樣。
在代碼 2 中,for 是放置陣列的最后一個值而不是邏輯代碼的相應值。
有人知道我該如何解決這個問題?謝謝
設定代碼:
import numpy as np
frete=600
estocagem=300
#Criar os vetores de Demanda e de Frequencia
vetordemanda=np.array([0,1000,2000,3000,4000,5000,6000,7000])
vetorfrequencia=np.array([0.01,0.05,0.1,0.14,0.26,0.3,0.1,0.04])
#Vetor de frequencia acumulada (Cumulative sum)
vetorfreqacumulada=np.cumsum(vetorfrequencia)
vetoraleatorio=np.random.rand(100)
vetordemandasim=np.zeros(100)
代碼 1:
for t in range(0,100):
if vetoraleatorio[t]<=vetorfreqacumulada[0]:
vetordemandasim[t]=vetordemanda[0]
elif vetoraleatorio[t]<=vetorfreqacumulada[1]:
vetordemandasim[t]=vetordemanda[1]
elif vetoraleatorio[t]<=vetorfreqacumulada[2]:
vetordemandasim[t]=vetordemanda[2]
elif vetoraleatorio[t]<=vetorfreqacumulada[3]:
vetordemandasim[t]=vetordemanda[3]
elif vetoraleatorio[t]<=vetorfreqacumulada[4]:
vetordemandasim[t]=vetordemanda[4]
elif vetoraleatorio[t]<=vetorfreqacumulada[5]:
vetordemandasim[t]=vetordemanda[5]
elif vetoraleatorio[t]<=vetorfreqacumulada[6]:
vetordemandasim[t]=vetordemanda[6]
else:
vetordemandasim[t]=vetordemanda[7]
代碼 2(不作業):
for t in range(0,100):
for i in range(0,7):
if vetoraleatorio[t]<=vetorfreqacumulada[i]:
vetordemandasim[t]=vetordemanda[i]
代碼 1 的結果:
0 - 4000
1 - 5000
2 - 4000
3 - 5000
5 - 1000
6 - 6000
7 - 4000
8 - 5000
...
代碼 2 的結果:
0 - 7000
1 - 7000
2 - 7000
3 - 7000
5 - 7000
6 - 7000
7 - 7000
8 - 7000
...
uj5u.com熱心網友回復:
這不起作用,因為if和elif它不會嘗試評估鏈中的每其他條件一個計算結果為true。在您的代碼中,它將無論如何評估每個條件。如果你想繼續使用你的方法,你需要在發現一個評估為真后跳出處理檢查的內部回圈。
您還缺少第一個示例的else.
if vetoraleatorio[t] <= vetorfreqacumulada[i]:
vetordemandasim[t] = vetordemanda[i]
break
# If we get here no condition was True
if i == 6:
vetordemandasim[t] = vetordemanda[7]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348095.html
