我是 python 新手,想知道反向倒数数组的值:
a = [1, 2, 3, 4]
def countdown_reversed(lists):
for x in reversed(lists):
print(x) # why is it x and not lists[x]?
countdown_reversed(list)
来自 Python 文档(https://docs.python.org/2/tutorial/controlflow.html)
Python 中的 for 语句与您在 C 或 Pascal 中可能使用的语句有些不同。Python 的 for 语句迭代任何序列的项目(列表或一个字符串),按照它们在序列中出现的顺序。
如果您需要当前列表元素的索引,您可以使用来自同一 url 的片段:
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]
结果:
0 Mary
1 had
2 a
3 little
4 lamb
您使用for
基于集合中的元素而不是索引的循环,例如:
chars = ['a', 'b', 't']
for char in chars:
print char
for i in range(len(chars)):
print chars[i]
当您使用
for a in b
python 时,一次返回 b 中的每个项目而不是索引。如果您需要索引,那么您可以使用带有 -1 作为第三个可选变量的范围函数,每次倒计时 1。不过要小心,因为在 python 中,范围将从起始值到但不包括最后一个值,因此为什么在这段代码中到处都是 -1
list = [1, 2, 3, 4]
def countdown_reversed(lists):
for x in range(len(lists)-1,-1,-1):
print(x) # will return index
print(lists[x]) # will return value
countdown_reversed(list)