这两种 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/