当它超出范围时开始列表

时间:2017-02-04 20:24:24

标签: python arrays

import time
from random import *
import random

rand = random.uniform(0.1,1)

letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]


run = input("Start? > ")
mins = 0

if run == "start":

    while mins != 60:

        print (">", letters[mins])

        time.sleep(rand)

        mins += 1

我希望列表一遍又一遍地开始,直到“分钟”达到60分。

2 个答案:

答案 0 :(得分:7)

一个简单的解决方案可能是尝试将索引更改为:

print (">", letters[mins%len(letters)])

%函数返回除法运算的余数。因此,在这种情况下,一旦分钟大于列表的长度,它就会重新开始。在索引0。

答案 1 :(得分:2)

您也可以使用itertools.cycle

  

itertools.cycle(iterable)

     

使迭代器从iterable返回元素并保存每个元素的副本。当iterable耗尽时,返回保存副本中的元素。无限期地重复。

而不是输入字母表中的所有(小写)字母,您可以使用字符串常量string.ascii_lowercase

import time
from itertools import cycle
from random import uniform
from string import ascii_lowercase

rand = uniform(0.1, 1) 
run = input("Start? > ")

if run == "start":
    for letter, _ in zip(cycle(ascii_lowercase), range(60)):
        print(">", letter)
        time.sleep(rand)