Python 将字符串输出更改为int以获得最大值?
我对python还很陌生,所以仍在掌握这门语言 我有下面的函数,它接受一个字符串,并将其应用到一个算法,该算法告诉我们它是否与模型1、2、3、4或5对齐 目前,这段代码:Python 将字符串输出更改为int以获得最大值?,python,string,type-conversion,Python,String,Type Conversion,我对python还很陌生,所以仍在掌握这门语言 我有下面的函数,它接受一个字符串,并将其应用到一个算法,该算法告诉我们它是否与模型1、2、3、4或5对齐 目前,这段代码: def apply_text(text): test_str = [text] test_new = tfidf_m.transform(test_str) prediction = 0 for m in range(0,5): percentage = '{P:.1%}'.fo
def apply_text(text):
test_str = [text]
test_new = tfidf_m.transform(test_str)
prediction = 0
for m in range(0,5):
percentage = '{P:.1%}'.format(M=cat[m], P=lr_m[m].predict_proba(test_new)[0][1])
print(percentage)
并运行以下函数:apply_text(“糟糕的主意”)
提供以下输出:
71.4%
33.1%
2.9%
1.6%
4.9%
模型1=71.4%,模型2=33.1%。。。模型5=4.9%
我只想输出百分比最高的型号。所以在上面的例子中,答案是1
,因为这有71.4%。
由于输出是字符串类型,我发现很难找到方法将其转换为
int
,然后比较每个值(可能在某种循环中)以获得最大值尝试将值放入列表中,然后可以使用列表方法:
百分比=[]
对于范围(0,5)内的m:
percentage.append({P:.1%}).格式(M=cat[M],P=lr_M[M].预测概率(test_new)[0][1]))
打印(*百分比,sep='\n')
打印('型号上的最大值',百分比索引(最大值(百分比)))
或使用字典:
percentage={}
对于范围(0,5)内的m:
百分比['Model'+str(m)]='{P:.1%}'。格式(m=cat[m],P=lr_m[m]。预测概率(test_new)[0][1])
打印(*百分比,sep='\n')
打印('Max on',Max(percentage.keys(),key=(lambda key:percentage[key]))
尝试将值放入列表中,然后可以使用列表方法:
百分比=[]
对于范围(0,5)内的m:
percentage.append({P:.1%}).格式(M=cat[M],P=lr_M[M].预测概率(test_new)[0][1]))
打印(*百分比,sep='\n')
打印('型号上的最大值',百分比索引(最大值(百分比)))
或使用字典:
percentage={}
对于范围(0,5)内的m:
百分比['Model'+str(m)]='{P:.1%}'。格式(m=cat[m],P=lr_m[m]。预测概率(test_new)[0][1])
打印(*百分比,sep='\n')
打印('Max on',Max(percentage.keys(),key=(lambda key:percentage[key]))
我认为您希望将百分比与型号一起保存,对其进行排序,然后返回最高值
这可以通过以下方式实现:
def apply_text(text):
test_str = [text]
test_new = tfidf_m.transform(test_str)
prediction = 0
percentage_list = []
for m in range(0,5):
percentage = '{P:.1}'.format(M=cat[m], P=lr_m[m].predict_proba(test_new)[0][1])
percentage_list.append([m+1, float(percentage)])
percentage_list.sort(reverse=True, key=lambda a: a[1])
return percentage_list[0][0]
注意事项:
precentage\u列表的最后一个元素
我认为您希望将百分比与型号一起保存,对其进行排序,然后返回最高值 这可以通过以下方式实现:
def apply_text(text):
test_str = [text]
test_new = tfidf_m.transform(test_str)
prediction = 0
percentage_list = []
for m in range(0,5):
percentage = '{P:.1}'.format(M=cat[m], P=lr_m[m].predict_proba(test_new)[0][1])
percentage_list.append([m+1, float(percentage)])
percentage_list.sort(reverse=True, key=lambda a: a[1])
return percentage_list[0][0]
注意事项:
precentage\u列表的最后一个元素
尝试将所有百分比值存储在一个字典中,模型号作为键,百分比作为值:dictionary={'model_1':pct_value_1,'model_2':pct_value_2}等等。然后按降序对数据排序,并获取第一个键:值对。尝试将所有百分比值存储在一个字典中,模型号作为键,百分比作为值:字典={'model_1':pct_value_1,'model_2':pct_value_2}等等。然后按降序对数据排序并获取第一个键:值对。