【问题标题】:Which is the better way to write this code? [closed]编写此代码的更好方法是什么? [关闭]
【发布时间】:2019-09-16 15:37:16
【问题描述】:

这是一个简单的代码,用于查找并打印在第一个之后出现的最后一个“zip”的位置,因此如果没有找到“zip”或者它只出现一次它应该打印 -1。我写了两个可以做同样事情的代码,我想知道哪个代码更好,为什么以及如何改进它(除了添加 cmets)。

一开始我写了这段代码

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

然后我在这条提示之后编写了第二个代码: " print (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

我可以看到第一个代码更大,但我不知道这是否是更好的编码方式。如果代码更短,总是更好吗? 请给我你的意见,哪个是更好的代码。

两个代码给出相同的结果,没有错误。

【问题讨论】:

标签: python performance data-structures structure performance-testing


【解决方案1】:

其实你可以写单行

indicator = text.rfind('zip') if text.count('zip')>1 else -1

【讨论】:

  • 哇,这很容易。我是一个初学者,不知道python中有内置的方法可以做到这一点,我并没有真正想到这一点。太感谢了。无论如何,如果没有内置方法可以做到这一点,我不得不自己构建这些方法,也许在不同的场景中,哪个代码更好?哪一个结构更好,更容易理解?将来我应该如何编写代码?还有其他建议吗?
  • 第二个看起来更好。但你总能写出更好的解决方案。尝试更多并了解更多:) 关于什么是好的代码。这是一个链接。 stackoverflow.com/questions/366588/…
猜你喜欢
  • 2010-12-08
  • 2021-02-14
  • 2018-05-30
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 2013-01-14
  • 2017-08-19
  • 1970-01-01
相关资源
最近更新 更多