在循环中迭代字符串中的每个第 n 个元素 - python

2022-01-24 00:00:00 python string loops iteration

问题描述

如何遍历字符串中的每个第二个元素?

一种方法是(如果我想遍历第 n 个元素):

One way to do this would be(If I want to iterate over nth element):

sample = "This is a string"
n = 3 # I want to iterate over every third element
i = 1
for x in sample:
    if i % n == 0:
        # do something with x
    else:
        # do something else with x
    i += 1

是否有任何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:

sample = "This is a string"
n = 3 # I want to iterate over every third element
for i,x in enumerate(sample):
    if i % n == 0:
        print("do something with x "+x)
    else:
        print("do something else with x "+x)

注意它不是从 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:

import itertools
for s in itertools.islice(sample,None,None,n):
    print(s)

结果:

T
s
s

r
g

相关文章