编写此代码的更好方法是什么?
Which is the better way to write this code?
这是一个简单的代码,用于查找和打印第一个出现后最后一次出现的 "zip" 的位置,因此如果没有找到 "zip" 或者它只出现一次,它应该打印 - 1.我写了两个可以做同样事情的代码,我想知道哪个代码更好,为什么以及如何改进它(除了添加注释)。
起初我写了这段代码
text = 'all zip files are zipped'
indicator = 0
zip_position = text.find("zip" , indicator)
printer = zip_position
cycles = 0
printer_confirmation = 0
while zip_position != -1:
printer = zip_position
zip_position = text.find("zip" , indicator)
indicator = zip_position + 1
if printer > zip_position and cycles > 1:
print printer
printer_confirmation = 1
cycles += 1
if cycles < 3 and printer_confirmation != 1:
print -1
然后我在提示后写了第二个代码是这一行:
" 打印 (text.find('zip', text.find("zip")+1)) "
我的完整代码:
text = "all zip files are zipped"
indicator = 1
zip_position = (text.find('zip', text.find("zip")+indicator))
while zip_position != -1:
zip_position = (text.find('zip', text.find("zip")+indicator))
indicator += 1
if zip_position == -1 and text.find("zip" , text.find("zip")+(indicator - 2)) > text.find('zip'):
indicator -= 2
zip_position = (text.find('zip', text.find("zip")+indicator))
print zip_position
我可以看到第一个代码更大,但我不知道它是否是更好的编码方式。代码越短越好吗?
请给我你的意见,哪个是更好的代码。
两个代码给出相同的结果,没有错误。
其实你可以写一行
indicator = text.rfind('zip') if text.count('zip')>1 else -1
这是一个简单的代码,用于查找和打印第一个出现后最后一次出现的 "zip" 的位置,因此如果没有找到 "zip" 或者它只出现一次,它应该打印 - 1.我写了两个可以做同样事情的代码,我想知道哪个代码更好,为什么以及如何改进它(除了添加注释)。
起初我写了这段代码
text = 'all zip files are zipped'
indicator = 0
zip_position = text.find("zip" , indicator)
printer = zip_position
cycles = 0
printer_confirmation = 0
while zip_position != -1:
printer = zip_position
zip_position = text.find("zip" , indicator)
indicator = zip_position + 1
if printer > zip_position and cycles > 1:
print printer
printer_confirmation = 1
cycles += 1
if cycles < 3 and printer_confirmation != 1:
print -1
然后我在提示后写了第二个代码是这一行: " 打印 (text.find('zip', text.find("zip")+1)) "
我的完整代码:
text = "all zip files are zipped"
indicator = 1
zip_position = (text.find('zip', text.find("zip")+indicator))
while zip_position != -1:
zip_position = (text.find('zip', text.find("zip")+indicator))
indicator += 1
if zip_position == -1 and text.find("zip" , text.find("zip")+(indicator - 2)) > text.find('zip'):
indicator -= 2
zip_position = (text.find('zip', text.find("zip")+indicator))
print zip_position
我可以看到第一个代码更大,但我不知道它是否是更好的编码方式。代码越短越好吗? 请给我你的意见,哪个是更好的代码。
两个代码给出相同的结果,没有错误。
其实你可以写一行
indicator = text.rfind('zip') if text.count('zip')>1 else -1