简体   繁体   English

在 Python 中使用 enumerate() 将索引旋转回 `for` 循环中的第一个元素的更好方法

[英]Better way to rotate index back to first element in `for` loop with enumerate() in Python

I hope more experienced users in Python will be able to help me make this more efficient:我希望 Python 中更多有经验的用户能够帮助我提高效率:

If I need cyclic operations, for example if the last element of an array needs to be connected to the first element in an enumerated loop, is there a better way to do this than the following?如果我需要循环操作,例如,如果数组的最后一个元素需要连接到枚举循环中的第一个元素,是否有比以下方法更好的方法?

foo=['tic', 'tac', 'toe']
for i, v in enumerate(foo):
    if i<len(foo)-1:
        print(i, v,foo[i+1])
    else:
        print(i, v,foo[0])

This elementary method will get more complicated if more than one element rolling is required let's say to get such a result:如果需要多个元素滚动,这个基本方法将变得更加复杂让我们假设要得到这样的结果:

 0 tic tac toe
 1 tac toe tic  
 2 toe tic tac

Speaking of rolling, I looked into numpy.roll but that seems to be creating new arrays (I think?) which I am trying to avoid if possible.说到滚动,我查看了numpy.roll但这似乎正在创建新的 arrays(我认为?),如果可能的话我会尽量避免。

Please note that this could be something such as sin(foo[i])*foo[i+1] or other complicated calculations that need a connection back to the first elements and this example from the pyhton.org website may be misleading as I am not looking for permutations.请注意,这可能是诸如sin(foo[i])*foo[i+1]之类的东西或其他需要连接回第一个元素的复杂计算,并且来自 pyhton.org 网站的这个示例可能会产生误导,因为我我不是在寻找排列。

You can do it with slicing.你可以通过切片来做到这一点。 This will work with any array size这适用于任何数组大小

foo = ['tic', 'tac', 'toe']
for i in range(len(foo)):
    print(i, ' '.join(foo[i:] + foo[:i]))

Output Output

0 tic tac toe
1 tac toe tic
2 toe tic tac

whenever you go circular on a linear range, I try to think of modular arithmetic每当你 go 线性范围内的循环时,我试着想到模运算

foo=['tic', 'tac', 'toe', 'baz', 'bar']

roll_factor = 2

for i in range(len(foo)):
    print(foo[(i + roll_factor) % len(foo)])

you can change roll_factor for rolling more than one element您可以更改roll_factor以滚动多个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM