这是一种方法:
with open('file.txt', 'r') as p:
lst = p.read().splitlines() # List all the lines of the file
lst2 = [float(i.split(', ')[1]) for i in lst[1:]] # List all the floats
num = [round(a*9/max(lst2))+1 for a in lst2] # List all the scaled numbers
for i,(l,n) in enumerate(zip(lst,['scaled_value']+num)):
lst[i] = f"{l}, {n}" # Add the 'scaled_value' column
with open('file.txt', 'w') as p:
p.write('\n'.join(lst)) # Write the updated data into the file
之前:
url, value
https://mywebsite.com/p/1, 0.00212
https://mywebsite.com/p/2, 0.00208
https://mywebsite.com/p/3, 0.00201
https://mywebsite.com/p/4, 0.00138
https://mywebsite.com/p/5, 0.00067
https://mywebsite.com/p/1, 0.00001
之后:
url, value, scaled_value
https://mywebsite.com/p/1, 0.00212, 10
https://mywebsite.com/p/2, 0.00208, 10
https://mywebsite.com/p/3, 0.00201, 10
https://mywebsite.com/p/4, 0.00138, 7
https://mywebsite.com/p/5, 0.00067, 4
https://mywebsite.com/p/1, 0.00001, 1
更新:
我的代码中进行转换的部分是:
num = [round(a*9/max(lst2))+1 for a in lst2]
其中lst2 只是从文件中提取的浮点数列表。您为我更新了问题以解释两者之间的区别
res1 = round(x*9/maxpri)+1
res2 = round(((x-minpri)/(maxpri-minpri))*10, 2)
让我们先看看我的列表理解:
num1 = [round(x*9/max(lst2))+1 for x in lst2]
num2 = [round(((x-min(lst2))/(max(lst2)-min(lst2)))*10, 2) for x in lst2]
print(num1)
print(num2)
输出:
[10, 10, 10, 7, 4, 1]
[10.0, 9.81, 9.48, 6.49, 3.13, 0.0]
第一个最明显的区别是我将答案四舍五入到最接近的整数。没有它,它将是:
num1 = [round(x*9/max(lst2), 2)+1 for x in lst2]
num2 = [round(((x-min(lst2))/(max(lst2)-min(lst2)))*10, 2) for x in lst2]
print(num1)
print(num2)
输出:
[10.0, 9.83, 9.53, 6.86, 3.84, 1.04]
[10.0, 9.81, 9.48, 6.49, 3.13, 0.0]
这些值现在非常接近,但还有一件事。我的代码假定缩放值的最小值是1,因为我在您的帖子https://mywebsite.com/p/1, 0.00001, 1 中看到了。我现在意识到你说的是 0-10,而不是 1-10。所以另一个是将9(10-1=9)更改为10(10-0=10),并删除+1:
round(x*9/max(lst2), 2)+1
round(x*10/max(lst2), 2)
num1 = [round(x*10/max(lst2), 2) for x in lst2]
num2 = [round(((x-min(lst2))/(max(lst2)-min(lst2)))*10, 2) for x in lst2]
print(num1)
print(num2)
输出:
[10.0, 9.81, 9.48, 6.51, 3.16, 0.05]
[10.0, 9.81, 9.48, 6.49, 3.13, 0.0]
还有一点不同,那是因为我假设您的列中的最小值是0,因为您没有显示整个数组。但在这种情况下,它是0.00001。所以,继续:
num = [round(((x-min(lst2))/(max(lst2)-min(lst2)))*10, 2) for x in lst2]
总结:我的代码假设您希望数字从 1 缩放到 10,而不是 0 到 10,并且我的代码假设您的数据的最小值为 0,但情况可能并非如此。