python - "if"和 "if not"之间的性能或风格差异?

标签 python performance if-statement coding-style

这两种 if 语句的编写方式是否存在性能差异或风格偏好?基本上是一样的,第一个条件只会满足一次,而另一个条件会每隔一段时间满足一次。只满足一次的条件应该是第一还是第二?它对性能有影响吗?如果性能相同,我更喜欢第一种方式。

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    chunk = min(max_chunk,length-offset)
    if chunk < max_chunk:
        write_data(data[offset:])
    else:
        write_data(data[offset:offset+max_chunk])

对比

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    chunk = min(max_chunk,length-offset)
    if not chunk < max_chunk:
        write_data(data[offset:offset+max_chunk])
    else:
        write_data(data[offset:])

最佳答案

在您的示例中,if 根本不需要:

data = range[0,1023]
length = len(data)
max_chunk = 10

for offset in xrange(0,length,max_chunk):
    write_data(data[offset:offset+max_chunk]) # It works correctly

我认为这是您的情况下最有效的方法。

关于python - "if"和 "if not"之间的性能或风格差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12680109/

相关文章:

python - 如何删除列表[:] works

php - 定制 CMS 还是第三方?

python - 具有多个值列的 Pandas 融化数据框

mysql - 加快创建mysql表(from select)

android - 在 while 循环中读取 SharedPreferences 的坏习惯?

performance - 分母已知时更快的整数除法?

bash - 如何检查数字是否在shell中的范围内

javascript - 区分循环中两个不同的 Action

java - 1. java ')'预期错误+ 2.不含 'else'的 'if'

python - KivyMD:工具栏在 Android 上不起作用。应用程序崩溃