如何缩短文件写入的ifelse代码?

2024-05-15 00:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

请您提出改进建议,使代码更简洁:

item_avg = item/(num_ti - 1)
if item_avg < 5002 :
   tfp.write("%s\n", %item_avg)
else:
   tfp.write("%s\n", %"5001")

Tags: 代码iftiitemelsenum建议write
3条回答

它认为您希望使代码看起来更像Python,因此不需要使用if语句,因此考虑到您使用的是Python 3.6+,您可以通过以下方式简化此代码:

item_avg = item /(num_ti - 1)
tpf.write(f'{item_avg if item_avg < 5002 else 5001}\n')

否则,可以使用format

item_avg = item /(num_ti - 1)
tpf.write('{}\n'.format(item_avg if item_avg < 5002 else 5001)

这不是太多的分拣机,但这节省了你一行。我更喜欢使用字符串连接而不是格式化。不过,两者都应该管用。你知道吗

if item_avg >= 5002 : item_avg = 5001 tfp.write(str(item_avg) + '\n')

因为item_avg看起来是一个整数值,所以可以让min内置函数执行if工作。只需在代码中打印所需的值。你知道吗

item_avg = item/(num_ti - 1)
tfp.write(str(min(item_avg, 5001)) + '\n')

。。。或者更简单的版本

print(min(item_avg, 5001), file = tfp)

相关问题 更多 >

    热门问题