如何使交替' for'环形?
如何为``'''循环做出交替步骤? IE编号序列(-1,2,-3,4,-5)
我知道如何使所有负数使
n=int(input())
for i in range (1,n+1):
i=i*(-1)
print(i)
我确定有更好的方法可以做到这一点,但是我如何为n = 2迈出第二步,4,6 ...?将另一个i = i*( - 1)又一次+
How do i make alternating step for a 'for' loop? i.e number sequence (-1,2,-3,4,-5)
I know how to make all negative which is
n=int(input())
for i in range (1,n+1):
i=i*(-1)
print(i)
im sure there's a better way to do it, but how do i make a 2nd step on for the n=2,4,6... ? putting another i=i*(-1) makes it all+ again
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以引入奇偶校验检查,即检查当前介绍的
i
的值是否均匀或奇怪。这可以使用Modulo操作员%
来实现。You could introduce a parity check, i.e. check whether the value of
i
of the current interation is even or odd. This can be achieved using the modulo operator%
.使用数学
奇数是负数,-1到奇数的功率为-1,因此我们将奇数数乘以(-1)^i
对于偶数数字的方式相同,因为-1偶数供电为+1,因此通常在我们的情况下,每个数字都来自< 1、2、3、4,...>地图为< -1,2,-3,4,...>
Use math
odd numbers are negative, -1 to power of a odd number is -1 so we multiply odd numbers by (-1)^i
same way for even numbers because -1 to power of even is +1 so generally in our case each number from <1, 2, 3, 4, ...> maps to <-1, 2, -3, 4, ...>
将-1升至-1甚至+1的力量。取决于您要“奇数数负”或“第一个第三五个数字”负。
您也可以只维护一个“翻转”:
您可以使用
itertools.cycle()
与
的列表[ - 1,1]
和zip
它的范围。Raising -1 to odd powers for -1 and even powers for +1 is how I'd do it. Depends on if you want "odd numbers negative" or "first third fifth numbers" negative.
You could also just maintain a "flip":
You can use
itertools.cycle()
with list of[-1, 1]
andzip
it with your range.考虑这个问题的另一种方法是,您有两个序列,一个正值之一,一个负面值,而在它们之间产生结果。也就是说,您交流来自这些序列的值。第三方 toolz 库具有许多有用的功能,例如<
Interleave
:Another way to think about this problem is that you have two sequences, one of positive values, one of negative ones and you alternate between them for producing the result. That is, you interleave values from those sequences. The third-party Toolz library has lots of useful functions, like
interleave
:我添加了是否可以检查数字的部分。它提供了与-1相乘的奇数。
I added if part that checks the number not even. It provides odd numbers to multiply with -1.