慕森卡
这是一种方法:with open('file.txt', 'r') as p: lst = p.read().splitlines() # List all the lines of the filelst2 = [float(i.split(', ')[1]) for i in lst[1:]] # List all the floatsnum = [round(a*9/max(lst2))+1 for a in lst2] # List all the scaled numbersfor i,(l,n) in enumerate(zip(lst,['scaled_value']+num)): lst[i] = f"{l}, {n}" # Add the 'scaled_value' columnwith open('file.txt', 'w') as p: p.write('\n'.join(lst)) # Write the updated data into the file前:url, valuehttps://mywebsite.com/p/1, 0.00212https://mywebsite.com/p/2, 0.00208https://mywebsite.com/p/3, 0.00201https://mywebsite.com/p/4, 0.00138https://mywebsite.com/p/5, 0.00067https://mywebsite.com/p/1, 0.00001后:url, value, scaled_valuehttps://mywebsite.com/p/1, 0.00212, 10https://mywebsite.com/p/2, 0.00208, 10https://mywebsite.com/p/3, 0.00201, 10https://mywebsite.com/p/4, 0.00138, 7https://mywebsite.com/p/5, 0.00067, 4https://mywebsite.com/p/1, 0.00001, 1更新:我的代码中进行转换的部分是:num = [round(a*9/max(lst2))+1 for a in lst2]wherelst2只是从文件中提取的浮点数列表。您为我更新了问题以解释两者之间的区别res1 = round(x*9/maxpri)+1res2 = 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。因此,另一个是将 (10-1=9) 更改9为10(10-0=10),并删除+1:round(x*9/max(lst2), 2)+1round(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,但事实可能并非如此。