我想知道我是否可以在python中使用循环使其成为单个代码块,可以抓取我best_result1_conf
,best_result2_conf
和best_result3_conf
。
if best_score1 == '1.0':
best_result1_conf='High'
elif best_score1 > '0.85' and best_score1 < '1.0':
best_result1_conf='Medium'
else: best_result1_conf='Low'
if best_score2 == '1.0':
best_result2_conf='High'
elif best_score2 > '0.85' and best_score2 < '1.0':
best_result2_conf='Medium'
else: best_result2_conf='Low'
if best_score3 == '1.0':
best_result3_conf='High'
elif best_score3 > '0.85' and best_score3 < '1.0':
best_result3_conf='Medium'
else: best_result3_conf='Low'
答案 0 :(得分:2)
作为一项功能:
def s_to_r(s):
if 0.85 < s < 1.0:
return "Medium"
elif s == 1.0:
return "High"
else:
return "Low"
results = [s_to_r(score) for score in [best_score1, best_score2, best_score3] ]
虽然通常这是我想引入OOP的时候。我假设这些得分属于某人,所以也许:
class Competitor(object):
def __init__(self, name):
self.name = name
self.scores = list()
def addScore(self,score):
self.scores.append(score)
def _getScoreValue(self,index):
score = self.scores[index]
if score <= 0.85:
return "Low"
elif 0.85 < score < 1.0:
return "Medium"
else:
return "High"
def getScore(self,index):
return {"score":self.scores[index],"value":_getScoreValue(index)}
这将允许您执行以下操作:
competitors = [Competitor("Adam"),Competitor("Steven"),Competitor("George"),
Competitor("Charlie"),Competitor("Bob"),Competitor("Sally")]
# generating test data
for competitor in competitors:
for _ in range(5):
competitor.addScore(round(random.random(),2))
# generating test data
for competitor in competitors:
for i,score in enumerate(competitor.scores):
if i==0: name = competitor.name
else: name = ""
print("{name:20}{scoredict[score]:<7}{scoredict[value]}".format(name=name,
scoredict=competitor.getScore(i)))
答案 1 :(得分:0)
您可以使用列表。
best_scores = [1.0, 0.9, 0.7]
results = []
for score in best_scores:
if score == 1.0:
results.append('High')
elif score > 0.85 and score < 1.0:
results.append('Medium')
else:
results.append('Low')
答案 2 :(得分:0)
使用功能:
def find_result(result):
if result > 1.0:
print(“Cannot calculate”)
elif result == 1.0:
word_result = ‘High’
elif result > 0.85:
word_result = ‘Medium’
else:
word_result = ‘Low’
return word_result
best_result1_conf = find_result(best_score1)
best_result2_conf = find_result(best_score2)
best_result3_conf = find_result(best_score3)
希望这有帮助!