Pythonic方式遍历从1开始的范围 [英] Pythonic way to iterate through a range starting at 1

查看:73
本文介绍了Pythonic方式遍历从1开始的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,如果我想通过 n 迭代 1 ,我可能会使用以下方法:

for _ in range(1, n+1):
    print(_)

是否有一种更清洁的方法来完成此操作而不必引用 n + 1 ?

奇怪的是,如果要迭代通常从1开始的范围(这并不罕见),我必须指定两次递增:

  1. 1置于范围的开头.
  2. + 1位于范围的末尾.

解决方案

range(1, n+1)不被认为是重复的,但是我可以看到,如果要将1更改为另一个数字,这可能会很麻烦. >

这将使用生成器删除重复项:

for _ in (number+1 for number in range(5)):
    print(_)

Currently if I want to iterate 1 through n I would likely use the following method:

for _ in range(1, n+1):
    print(_)

Is there a cleaner way to accomplish this without having to reference n + 1 ?

It seems odd that if I want to iterate a range ordinally starting at 1, which is not uncommon, that I have to specify the increase by one twice:

  1. With the 1 at the start of the range.
  2. With the + 1 at the end of the range.

解决方案

range(1, n+1) is not considered duplication, but I can see that this might become a hassle if you were going to change 1 to another number.

This removes the duplication using a generator:

for _ in (number+1 for number in range(5)):
    print(_)

这篇关于Pythonic方式遍历从1开始的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆