以相反的顺序在新行上打印列表中的元素



我想以相反的顺序打印此列表中的所有元素,并且此列表中的每个元素都必须在新行上。例如,如果列表是['i','am','programming','with','python'],它应该打印出来:蟒跟编程是我最好的方法是什么?

def list():
    words = []
    while True:
        output = input("Type a word: ")
        if output == "stop":
            break
        else:
            words.append(output)
    for elements in words:
        print(elements)
list()

泛型:

for(i=wordsArry.size();i--;i<0){
    pritnln(wordsArry[i]+"/n")
}
  • 从列表末尾开始迭代 - 列表中的最后一个元素。
  • 然后向后迭代 - 将迭代器减少 1,直到达到 0。
  • 打印每个元素加上新行符号 - 可能取决于操作系统,语言。

在 Python 中,您可以通过以下方式反转列表:

words = ['i', 'am', 'programming', 'with', 'python']
words.reverse()
for w in words:
    print(w)

如果要反向迭代但保持原始顺序,可以使用切片:

for w in words[::-1]:
    print(w)

切片语法为 [begin:end:step],其中省略了 begin (包括( 和 end (excl( 索引(获取所有元素(,步骤 -1 以相反的顺序返回包含元素的切片。

这两种方法产生相同的输出。

最新更新