计算每个更新值及其对应的随机变量,然后绘制它们的图形

2024-04-26 22:56:01 发布

您现在位置:Python中文网/ 问答频道 /正文

import random
#import matplotlib.pyplot as plt

a1 = ['','','?','']
a2 = [10,25,43.34,90]

i = 0
i_array = []
while i < 10:
    i_array.append(i)
    i = i + 1
    r = random.random()
    for i, j in enumerate(a1):
        if j == '?':
            print(a2[i]*r)
            a3 = a2[i]*r

plt.line(r,a3)

我在a1中的问号可能在这四个地方中的任何一个地方。因此,a2中对应的值需要更改。 答案是: 随机导入 #导入matplotlib.pyplot作为plt

a1 = ['','','?','']
a2 = [10,25,43.34,90]
xarray=[]
yarray=[]
i = 0
i_array = []#probably can delete this, I don't see any reason for it
for i in range(0,10):#use a for loop instead
    i_array.append(i)
    r = random.random()
    a3 = a2[a1.index('?')]*r#index here instead of the for loop
    print(a3)#since your assigning a3 anyway, might as well print that
    xarray.append(r)#plot needs arrays
    yarray.append(a3)
plt.plot(xarray,yarray)#plot your arrays

Tags: importa2forplotmatplotliba1pltrandom
1条回答
网友
1楼 · 发布于 2024-04-26 22:56:01

你能详细说明一下你在这里想做什么吗?似乎您正试图根据a1中包含“?”的位置在a2中选择一个值,然后将a2[的索引]相乘?在a1]中,用一个随机数,并用y轴上的乘积和x轴上的随机数作图。基于这一假设,有几种选择。最明显的是使用index()方法,请参见以下问题:Python: finding an element in an array。或者,如果“?”也要随机放置在a1中,那么随机查找a2的索引比使用两个列表更简单。使用以下a2[random.ranint(0, len(a2)-1)]执行此操作(这里的文档:https://docs.python.org/2/library/random.html)另外,我不是pyplot的专家,但您对plt.line(r,a3)的调用可能无法按您所希望的那样工作。基于我认为您要做的事情,您可能希望在循环的每个迭代中将r和a3附加到两个单独的列表(例如rlist、a3list),然后调用plt.plot(rlist, a3list)。最后,您的while循环并没有错,但是您似乎将它用作for循环,所以您最好还是这样做(for i in range(0,10):

相关问题 更多 >