简体   繁体   English

如何避免在 for 循环中声明未使用的变量?

[英]How can I get around declaring an unused variable in a for loop?

If I have a list comprehension (for example) like this:如果我有这样的列表理解(例如):

['' for x in myList]

Effectively making a new list that has an empty string for every element in a list, I never use the x .有效地为列表中的每个元素创建一个具有空字符串的新列表,我从不使用x Is there a cleaner way of writing this so I don't have to declare the unused x variable?有没有更简洁的写法,这样我就不必声明未使用的x变量?

_ is a standard placeholder name for ignored members in a for-loop and tuple assignment, eg _是 for 循环和元组赋值中被忽略成员的标准占位符名称,例如

['' for _ in myList]

[a+d for a, _, _, d, _ in fiveTuples]

BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.).顺便说一句,您的列表可以在没有列表理解的情况下编写(假设您想要制作一个不可变成员的列表,如字符串、整数等)。

[''] * len(myList)

No. As the Zen puts it: Special cases aren't special enough to break the rules.不。正如禅宗所说:特殊情况不足以打破规则。 The special case being loops not using the items of the thing being iterated and the rule being that there's a "target" to unpack to.特殊情况是循环不使用被迭代的事物的项目,规则是有一个“目标”要解包。

You can, however, use _ as variable name, which is usually understood as "intentionally unused" (even PyLint etc. knows and respect this).但是,您可以使用_作为变量名,这通常被理解为“有意未使用”(甚至 PyLint 等都知道并尊重这一点)。

It turns out that using dummy* (starting word is dummy) as the variable name does the same trick as _ .事实证明,使用dummy* (起始词是 dummy)作为变量名与_具有相同的技巧。 _ is a known standard and it would be better to use meaningful variable names. _是一个已知的标准,最好使用有意义的变量名。 So you can use dummy , dummy1 , dummy_anything .所以你可以使用dummydummy1dummy_anything By using these variable names PyLint won't complain.通过使用这些变量名, PyLint不会抱怨。

Add the following comment after the for loop on the same line:在同一行的 for 循环后添加以下注释:

#pylint: disable=unused-variable #pylint:禁用=未使用的变量

for i in range(100): #pylint: disable=unused-variable

If you need to name your arguments (in case, for example, when writing mocks that don't use certain arguments that are referenced by name), you can add this shortcut method:如果您需要命名您的参数(例如,在编写不使用按名称引用的某些参数的模拟时),您可以添加此快捷方法:

def UnusedArgument(_):
  pass

and then use it like this然后像这样使用它

def SomeMethod(name_should_remain):
  UnusedArgument(name_should_remain)

The generator objects don't actually use the variables.生成器对象实际上并不使用变量。 So something like所以像

list(('' for x in myList))

should do the trick.应该做的伎俩。 Note that x is not defined as a variable outside of the generator comprehension.请注意,x 未定义为生成器理解之外的变量。

You can also prepend a variable name with _ if you prefer giving the variable a human readable name.如果您更愿意为变量提供一个人类可读的名称,您也可以在变量名前加上_ For example you can use _foo , _foo1 , _anything and PyLint won't complain.例如,您可以使用_foo_foo1_anything并且 PyLint 不会抱怨。 In a for loop, it would be like:在 for 循环中,它会是这样的:

for _something in range(10):
    do_something_else()

edit: Add example编辑:添加示例

A verbose way is:一个详细的方法是:

newList = []
while len(newList) < len(mylist):
    newList.append('')

You avoid declaring an used variable this way.您可以避免以这种方式声明已使用的变量。

Also you can append both mutable and immutable objects (like dictionaries) into newList .您也可以将可变和不可变对象(如字典)附加到newList

Another thing for python newbies like me, '_', 'dummy' are a bit disconcerting.对于像我这样的 Python 新手来说,'_'、'dummy' 的另一件事有点令人不安。

Try it, it's simple:试试看,很简单:

# Use '_' instead of the variable
for _ in range(any_number):
    do_somthing()

Comment to How can I get around declaring an unused variable in a for loop?评论如何避免在 for 循环中声明未使用的变量? (Ran out of comment size) (评论大小用完了)

Python maintains the same reference for the object created. Python 为创建的对象维护相同的引用。 (irrespective of mutability),for example, (不考虑可变性),例如,

In [1]: i = 1

In [2]: j = 1

In [3]: id(i)
Out[3]: 142671248

In [4]: id(j)
Out[4]: 142671248

You, can see both i and j, refer to the same object in memory.What happens, when we change the value of one immutable variable.你可以看到 i 和 j 都指向内存中的同一个对象。当我们改变一个不可变变量的值时会发生什么。

In [5]: j = j+1

In [6]: id(i)
Out[6]: 142671248

In [7]: id(j)
Out[7]: 142671236

you can see j now starts to point a new location, (where 2 is stored), and i still points to location where 1 is stored.您可以看到 j 现在开始指向一个新位置(存储 2 的位置),而 i 仍然指向存储 1 的位置。 While evaluating,在评估时,

j = j+1

The value is picked from 142671248, calculated(if not already cached), and put at a new location 142671236. j is made to point to the new location.该值从 142671248 中选取,计算(如果尚未缓存),然后放在新位置 142671236 中。 j 指向新位置。 In simpler terms a new copy made everytime an immutable variable is modified.简单来说,每次修改不可变变量时都会创建一个新副本。

Mutability可变性

Mutable objects act little different in this regard.可变对象在这方面几乎没有什么不同。 When the value pointed by当指向的值

In [16]: a = []

In [17]: b = a

In [18]: id(a)
Out[18]: 3071546412L

In [19]: id(b)
Out[19]: 3071546412L

Both a and b point to the same memory location. a 和 b 都指向同一个内存位置。

In [20]: a.append(5)

Memory location pointed by a is modified. a 指向的内存位置被修改。

In [21]: a
Out[21]: [5]

In [22]: b
Out[22]: [5]

In [23]: id(a)
Out[23]: 3071546412L

In [24]: id(b)
Out[24]: 3071546412L

Both a and b, still point to the same memory location. a 和 b 仍然指向同一个内存位置。 In other word, mutable variables act of the same memory location pointed by the variable, instead of making a copy of the value pointed by the variable, like in immutable variable case.换句话说,可变变量的行为与变量指向的内存位置相同,而不是复制变量指向的值,就像在不可变变量的情况下一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python / PyCharm中明确声明变量未使用 - Explicitly declaring variable as unused in Python/PyCharm for循环中未使用的变量 - Unused variable in a for loop 如何在没有全局变量的情况下解决“ UnboundLocalError:赋值之前引用了本地变量&#39;foo&#39;”错误? - How can I get around “UnboundLocalError: local variable 'foo' referenced before assignment” errors without global variables? 未使用的变量&#39;i&#39;pylint(未使用的变量) - unused variable 'i' pylint(unused-variable) 将变量声明为float我得到java.lang.IllegalArgumentException:无法设置java.lang.Float字段 - Declaring a variable as float I get java.lang.IllegalArgumentException: Can not set java.lang.Float field 当for循环的变量有一段时间时,如何才能进入for循环的步骤 - How can I get step jump in for loop when it has a while conditioned on the for loop's variable Python:如何在未使用 X 分钟后删除变量? - Python: How can I delete a variable after being unused for X minutes? 我如何在循环中逐渐填充数组,而又不将其声明为Python中的1或零/空? - How can I fill gradually an array in a loop without declaring it as ones or zeros/empty in Python? 对于循环,如何在循环外使用循环变量 - For loop, how can i use loop variable outside loop 如何表示未使用的 function arguments? - How can I denote unused function arguments?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM