编辑-似乎我在计算测试零件的数量时犯了一个错误:
lines = len(file.readlines())
N = lines - 2
当我在一个单独的脚本中测试它时,它确实起了作用。。。你知道吗
初学者需要帮助。我的python脚本有个问题,我自己还没能解决。脚本应该从文本文件中读取浮点并进行一些计算。我无法将数字放入列表R[]
。你知道吗
下面是一个文本文件示例,其中第一行(s[0]
)是标称值,第二行(s[1]
)是公差,下面几行是一些电阻。你知道吗
3300.0美元
10.0美元
3132.0美元
3348.5美元
3557.3条
3467.4美元
3212.0美元
3084.6个
3324.0美元
我有以下代码:
R = []
Ntoolow = Nlow = Nhigh = Ntoohigh = 0.0
lines = 0
def find_mean(q):
tot = 0.0
c = len(q)
for x in range (c):
tot += q[x]
return tot/c
def find_median(q):
c = len(q)
if c%2:
return float(q[int(c/2)])
else:
c /= 2
return (q[int(c)]+q[int(c-1)])/2.0
file_name = input("Please enter the file name: ")
file = open(file_name, "r")
s = file.readlines()
Rnom = float(s[0])
Tol = float(s[1])
keepgoing = True
while keepgoing:
s = file.readline()
if s == "":
keepgoing = False
else:
R.append(float(s))
lines = len(file.readlines())
N = lines - 2
R.sort()
Rmin = R[0]
Rmax = R[N-1]
Rlowerlimit = Rnom - Tol
Rupperlimit = Rnom + Tol
for rn in R:
if rn < Rlowerlimit:
Ntoolow += 1
elif rn < Rnom:
Nlow += 1
elif rn <= Rupperlimit:
Nhigh += 1
else:
Ntoohigh += 1
Ptoolow = 100.0 * Ntoolow / N
Plow = 100.0 * Nlow / N
Phigh = 100.0 * Nhigh / N
Ptoohigh = 100.0 * Ntoohigh / N
Rmean = find_mean(R)
Rmedian = find_median(R)
print("Total number of parts tested: " + str(N))
print("The largest resistor is: " + str(Rmax) + " and the smallest is: " + str(Rmin))
print("The mean is: " + str(Rmean) + " and the median is: " + str(Rmedian))
print("The percentage of resistors that have too low tolerance is: " + str(Ptoolow) + "%")
print("The percentage of resistors that have low tolerance is: " + str(Plow) + "%")
print("The percentage of resistors that have high tolerance is: " + str(Phigh) + "%")
print("The percentage of resistors that have too high tolerance is: " + str(Ptoohigh) + "%")
file.close()
Python有许多库可以从CSV文件中读取信息,比如CSV、numpy和pandas。请尝试以下操作:
然后可以像这样迭代行:
跳过空行并用^{} 删除换行符
\n
:替换代码
用
它给了我答案。。。你知道吗
这是我编辑代码后的输出
相关问题 更多 >
编程相关推荐