展开元组/列表时不需要的部分 [英] Unneeded parts when unwrapping tuple/list

查看:49
本文介绍了展开元组/列表时不需要的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 就是编写漂亮的代码.所以,当我碰到一些东西时,我正在运行 pylint 来检查我的代码的美丽":

Python is all about writing beautiful code. So, I was running pylint to check the "beautifulness" of my code, when I bump into something:

未使用的变量myvar1"

Unused variable 'myvar1'

来自我代码的这一部分:

From this part of my code:

for myvar1, myvar2 in mylist:
    # Do stuff just using myvar2

mylist 是元组列表,因此我将元组解包为两个变量(myvar1myvar2).我定义这两个变量只是为了解开第二个变量,因为我不需要另一个.

mylist is a list of tuples, so I'm unwrapping the tuples into two variables (myvar1 and myvar2). I'm defining those two variables just to unwrap the second one, because I don't need the other.

所以,这是我的问题:有没有办法告诉解释器解开元组,但不解析第一部分(例如).在其他一些语言中,您可以执行以下操作:

So, here's my question: Is there a way to tell the interpreter to unwrap the tuple, but not assing the first part (for example). In some other languages you can do something like:

for _, myvar in mylist:
    # Do stuff with myvar

for *, myvar in mylist:
    # Do stuff with myvar

这意味着:我不关心元组的第一部分,我只需要第二部分.

注意:我知道这可能是我所要求的一个选项:

NOTE: I know that this could be an option for what I'm asking:

for mytuple in mylist:
    # Do stuff with mytuple[1]

但这远远不够可读.

推荐答案

除了@RaymondHettinger 的回答:如果变量名称以单个下划线开头,Pylint 也不会抱怨未使用的变量.这意味着您可以使用:

In addition to @RaymondHettinger's answer: Pylint also does not complain about unused variables if their names start with a single underscore. This means that you can use:

for _myvar1, myvar2 in mylist:

两全其美:

  • 没有 Pylint 警告,
  • 以及有关记录结构的信息

这也适用于函数/方法原型,并避免有关未使用参数的警告,当从 OO 框架中的基类派生时,您经常会收到警告.

This works for function / method prototypes too and avoids warnings about unused parameters, which you can often get when deriving from a base class in an OO framework.

这篇关于展开元组/列表时不需要的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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