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

Iterate over every nth element in string in loop - python(在循环中迭代字符串中的每个第 n 个元素 - python)
本文介绍了在循环中迭代字符串中的每个第 n 个元素 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

一种方法是(如果我想遍历第 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

这篇关于在循环中迭代字符串中的每个第 n 个元素 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)