gpt4 book ai didi

python - 提取值 >= 90% 的列

转载 作者:行者123 更新时间:2023-11-28 21:55:35 24 4
gpt4 key购买 nike

我编写此脚本是为了从我的 .txt 文件中提取具有 >= 90% 同一性的值。但是,该程序不考虑高于 100.00 的值,例如 100.05,这是为什么?

import re
output=open('result.txt','w')
f=open('file.txt','r')
lines=f.readlines()
for line in lines:
new_list=re.split(r'\t+',line.strip())
id_per=new_list[2]
if id_per >= '90':
new_list.append(id_per)
output.writelines(line)
f.close()
output.close()

输入文件示例

A   99.12
B 93.45
C 100.00
D 100.05
E 87.5

最佳答案

您应该将它们作为 float 而不是字符串进行比较。内容如下:

import re
output=open('result.txt','w')
f=open('file.txt','r')
lines=f.readlines()
for line in lines:
new_list=re.split(r'\t+',line.strip())
id_per=new_list[2]
if float(id_per) >= 90.0:
new_list.append(id_per)
output.writelines(line)
f.close()
output.close()

这是因为 python 比较将 numbers 解释为 strings,即使您希望将它们解释为 numbers。对于 strings,python 使用 ASCIIUnicode 规则逐个字符地进行比较。这就是为什么您的代码不会抛出任何错误,但它不会按照您期望的方式运行,使用 float 规则而不是 string 规则。

关于python - 提取值 >= 90% 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22659820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com