import time
r = range(2 << 20)
r_iter = iter(r)
b = time.time()
# while0
while True:
try:
i = next(r_iter)
except Exception:
break
print(time.time() - b)
count = 0
l = len(r)
b = time.time()
# while1
while count < l:
i = r[count]
count += 1
print(time.time() - b)
# while1用时约是while0的3倍
# 带索引值的for循环
# 使用enumerate内置对象生成一个带索引的二元组
# 要注意的是索引值在前
# (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
for i, x in enumerate([1, 2, 5, 10]):
# 此外,尽量不要将print放在循环体中
# 流的频繁开闭很消耗资源和影响效率
# 正确的处理方式是使用StringIO,将内容
# 全部写入,等待循环完毕后在外部打印
print(i, x)
# 用for循环实现一个死循环
s = '1'
for c in s:
s += c
# 这样不行,字符串是常量,它的更改是指针变更,for循环使用的还是
# 原来那块内存中的值
# 使用列表,拿一个,放一个来实现死循环
s = [1]
for c in s:
s.append(c)
Python中使用循环的几个小细节
最新推荐文章于 2024-05-14 11:00:23 发布