how do you make a For loop when you don't need index in python?

為{幸葍}努か 提交于 2019-12-08 17:51:36

问题


if i need a for loop in python

for i in range(1,42):
    print "spam"

but don't use the "i" for anything pylint complains about the unused variable. How should i handle this? I know you can do this:

for dummy_index in range(1,42):
    print "spam"

but doing this seems quite strange to me, is there a better way?

I'm quite new at python so forgive me if I'm missing something obvious.


回答1:


There is no "natural" way to loop n times without a counter variable in Python, and you should not resort to ugly hacks just to silence code analyzers.

In your case I would suggest one of the following:

  • Just ignore the PyLint warning (or filter reported warnings for one-character variables)
  • Configure PyLint to ignore variables named i, that are usually only used in for loops anyway.
  • Mark unused variables using a prefix, probably using the default _ (it's less distracting than dummy)



回答2:


for _ in range(1,42):
    print "spam"



回答3:


According to pylint documentation:

--dummy-variables-rgx=
          A regular expression matching names used for dummy variables (i.e.
          not used). [current: _|dummy]

In other words, if the name of the variable starts with an underscore, or with the letters dummy, pylint would not complain about the variable being unused:

for dummy in range(1, 42):
    print "spam"



回答4:


Usually you can work around it, just like this in your case:

>>> print "spam\n"*len(range(1,42))



回答5:


3 Simple Reasons

  1. There is no way to loop through your program without using a counter variable in a for loop.
  2. But you can create a program that goes from index[1] to index[2] just by adding if index[1]is done. return index[]+1.
  3. Unfortunately, you need to create an extra program which is not as efficient as the for loop and is not efficient in long programs.


来源:https://stackoverflow.com/questions/10122109/how-do-you-make-a-for-loop-when-you-dont-need-index-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!