while无限循环使用列表、元组、字典的另一类写法

0 阅读1分钟

# while无限循环使用列表、元组、字典的另一类写法

以一个红绿灯的示例为例:

  • 传统的写法如下:
import  time 
lights = [
    ("red",3),
    ("yellow",2),
    ("greed",4)
]

i=0
while True:
    c,s=lights[i]
    print(c)
    time.sleep(s)  #暂定时间
    if i==len(lights)-1:    #颜色循环切换
        i=0
    else:
        i+=1
  • python另一种写法要简洁得多
import time
from itertools import cycle  
lights = [
    ("red",3),
    ("yellow",2),
    ("greed",4)
]  # lights可以是集合,元组,列表等

colors=cycle(lights)
while True:
    c,s=next(colors)    # 不再需要手动管理索引,把颜色赋值给C,把时间赋值给S,NEXT读取下一条记录,当到尾部时,会自动指向第一条
    print(c)
    time.sleep(s)