如何遍历字符串中的每个第二个元素?
一种方法是(如果我想遍历第n个元素):
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
Thery是否有任何“ pythonic”方式做到这一点?(我很确定我的方法不好)
守着星空守着你
相关分类