有时,您需要在列表中的每个项目上执行代码。这叫做迭代,它可以用while循环和计数器变量来完成。 例如:
words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 结果: >>> hello! world! spam! eggs! >>>