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

2023-10-19Python开发问题
1

本文介绍了在循环中迭代字符串中的每个第 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11