问题:使用Python中的索引向后循环?
我正在尝试从100循环到0。如何在Python中执行此操作?
for i in range (100,0)
不起作用。
I am trying to loop from 100 to 0. How do I do this in Python?
for i in range (100,0)
doesn’t work.
回答 0
试试看range(100,-1,-1)
,第三个参数是要使用的增量(在此处记录)。
(此处记录了 “范围”选项,开始,停止,步骤)
Try range(100,-1,-1)
, the 3rd argument being the increment to use (documented here).
(“range” options, start, stop, step are documented here)
回答 1
我认为这是最易读的:
for i in reversed(xrange(101)):
print i,
In my opinion, this is the most readable:
for i in reversed(xrange(101)):
print i,
回答 2
for i in range(100, -1, -1)
和一些稍长(且较慢)的解决方案:
for i in reversed(range(101))
for i in range(101)[::-1]
for i in range(100, -1, -1)
and some slightly longer (and slower) solution:
for i in reversed(range(101))
for i in range(101)[::-1]
回答 3
通常在Python中,您可以使用负索引从背面开始:
numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
print numbers[-i - 1]
结果:
50
40
30
20
10
Generally in Python, you can use negative indices to start from the back:
numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
print numbers[-i - 1]
Result:
50
40
30
20
10
回答 4
为什么您的代码不起作用
您的代码for i in range (100, 0)
很好,除了
step
默认情况下,第三个参数()是+1
。因此,必须向range()指定第三个参数才能-1
向后退一步。
for i in range(100, -1, -1):
print(i)
注意:这在输出中包括100&0。
有多种方法。
更好的方法
对于pythonic方式,请检查PEP 0322。
这是Python3 pythonic示例,可从100打印到0(包括100和0)。
for i in reversed(range(101)):
print(i)
Why your code didn’t work
You code for i in range (100, 0)
is fine, except
the third parameter (step
) is by default +1
. So you have to specify 3rd parameter to range() as -1
to step backwards.
for i in range(100, -1, -1):
print(i)
NOTE: This includes 100 & 0 in the output.
There are multiple ways.
Better Way
For pythonic way, check PEP 0322.
This is Python3 pythonic example to print from 100 to 0 (including 100 & 0).
for i in reversed(range(101)):
print(i)
回答 5
另一个解决方案:
z = 10
for x in range (z):
y = z-x
print y
结果:
10
9
8
7
6
5
4
3
2
1
提示:如果您使用此方法对列表中的索引进行计数,则您希望从’y’值开始为-1,因为列表索引将从0开始。
Another solution:
z = 10
for x in range (z):
y = z-x
print y
Result:
10
9
8
7
6
5
4
3
2
1
Tip:
If you are using this method to count back indices in a list, you will want to -1 from the ‘y’ value, as your list indices will begin at 0.
回答 6
解决您的问题的简单答案可能是这样的:
for i in range(100):
k = 100 - i
print(k)
The simple answer to solve your problem could be like this:
for i in range(100):
k = 100 - i
print(k)
回答 7
for var in range(10,-1,-1)
作品
for var in range(10,-1,-1)
works
回答 8
简短而甜美。这是我参加codeAcademy类时的解决方案。以rev顺序打印字符串。
def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
Short and sweet. This was my solution when doing codeAcademy course. Prints a string in rev order.
def reverse(text):
string = ""
for i in range(len(text)-1,-1,-1):
string += text[i]
return string
回答 9
在您的情况下100 - i
,您始终可以增加范围并从变量中减去i in range( 0, 101 )
。
for i in range( 0, 101 ):
print 100 - i
You can always do increasing range and subtract from a variable in your case 100 - i
where i in range( 0, 101 )
.
for i in range( 0, 101 ):
print 100 - i
回答 10
我在一种代码学院练习中尝试过此操作(在不使用reversed或:: -1的情况下反转字符串中的字符)
def reverse(text):
chars= []
l = len(text)
last = l-1
for i in range (l):
chars.append(text[last])
last-=1
result= ""
for c in chars:
result += c
return result
print reverse('hola')
I tried this in one of the codeacademy exercises (reversing chars in a string without using reversed nor :: -1)
def reverse(text):
chars= []
l = len(text)
last = l-1
for i in range (l):
chars.append(text[last])
last-=1
result= ""
for c in chars:
result += c
return result
print reverse('hola')
回答 11
我想同时向后遍历两个列表,所以我需要负索引。这是我的解决方案:
a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
print(i, a[i])
结果:
-1 2
-2 5
-3 4
-4 3
-5 1
I wanted to loop through a two lists backwards at the same time so I needed the negative index. This is my solution:
a= [1,3,4,5,2]
for i in range(-1, -len(a), -1):
print(i, a[i])
Result:
-1 2
-2 5
-3 4
-4 3
-5 1
回答 12
哦,好吧,我读错了问题,我想这是关于在数组中向后移动吗?如果是这样,我有这个:
array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]
counter = 0
for loop in range(len(array)):
if loop <= len(array):
counter = -1
reverseEngineering = loop + counter
print(array[reverseEngineering])
Oh okay read the question wrong, I guess it’s about going backward in an array? if so, I have this:
array = ["ty", "rogers", "smith", "davis", "tony", "jack", "john", "jill", "harry", "tom", "jane", "hilary", "jackson", "andrew", "george", "rachel"]
counter = 0
for loop in range(len(array)):
if loop <= len(array):
counter = -1
reverseEngineering = loop + counter
print(array[reverseEngineering])
回答 13
您还可以在python中创建自定义反向机制。可以在任何地方用于循环迭代向后
class Reverse:
"""Iterator for looping over a sequence backwards"""
def __init__(self, seq):
self.seq = seq
self.index = len(seq)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.seq[self.index]
>>> d = [1,2,3,4,5]
>>> for i in Reverse(d):
... print(i)
...
5
4
3
2
1
You can also create a custom reverse mechanism in python. Which can be use anywhere for looping an iterable backwards
class Reverse:
"""Iterator for looping over a sequence backwards"""
def __init__(self, seq):
self.seq = seq
self.index = len(seq)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.seq[self.index]
>>> d = [1,2,3,4,5]
>>> for i in Reverse(d):
... print(i)
...
5
4
3
2
1
回答 14
a = 10
for i in sorted(range(a), reverse=True):
print i
a = 10
for i in sorted(range(a), reverse=True):
print i