Iterate over every nth element in string in loop - python(在循环中迭代字符串中的每个第 n 个元素 - python)
问题描述
如何遍历字符串中的每个第二个元素?
一种方法是(如果我想遍历第 n 个元素):
One way to do this would be(If I want to iterate over nth element):
是否有任何pythonic"方式来做到这一点?(我很确定我的方法不好)
Is thery any "pythonic" way to do this? (I am pretty sure my method is not good)
推荐答案
如果你想每隔 n 步做一些事情,其他情况下做其他事情,你可以使用 enumerate
来获取索引,并使用模数:
If you want to do something every nth step, and something else for other cases, you could use enumerate
to get the index, and use modulus:
注意它不是从 1 而是从 0 开始的.如果你想要别的东西,可以给 i
添加一个偏移量.
Note that it doesn't start at 1 but 0. Add an offset to i
if you want something else.
要仅对每个第 n 个元素进行迭代,最好的方法是使用 itertools.islice
来避免创建硬"字符串来仅对其进行迭代:
To iterate on every nth element only, the best way is to use itertools.islice
to avoid creating a "hard" string just to iterate on it:
结果:
这篇关于在循环中迭代字符串中的每个第 n 个元素 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!