pythonic方法在没有索引变量的情况下做N次? [英] pythonic way to do something N times without an index variable?

查看:29
本文介绍了pythonic方法在没有索引变量的情况下做N次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天都越来越喜欢python.

Every day I love python more and more.

今天,我正在编写一些代码,例如:

Today, I was writing some code like:

for i in xrange(N):
    do_something()

我不得不做 N 次某事.但是每次都不依赖于i(索引变量)的值.我意识到我正在创建一个我从未使用过的变量 (i),我想肯定有一种更 Pythonic 的方法可以做到这一点,而无需那个无用的索引变量."

I had to do something N times. But each time didn't depend on the value of i (index variable). I realized that I was creating a variable I never used (i), and I thought "There surely is a more pythonic way of doing this without the need for that useless index variable."

所以……问题是:你知道如何以更(pythonic)漂亮的方式完成这个简单的任务吗?

So... the question is: do you know how to do this simple task in a more (pythonic) beautiful way?

推荐答案

比在 xrange(N) 上循环稍快的方法是:

A slightly faster approach than looping on xrange(N) is:

import itertools

for _ in itertools.repeat(None, N):
    do_something()

这篇关于pythonic方法在没有索引变量的情况下做N次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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