展开元组/列表时不需要的部分

发布于 2024-12-19 09:43:27 字数 814 浏览 2 评论 0原文

Python 就是为了编写漂亮的代码。因此,当我遇到一些问题时,我正在运行 pylint 来检查代码的“美观性”:

未使用的变量“myvar1”

从我的代码的这一部分:

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

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

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

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

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

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

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

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

但到目前为止,它的可读性较差。

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

Unused variable 'myvar1'

From this part of my code:

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

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

or

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

That means: I don't care about the first part of the tuple, I just need the second one.

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

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

But that's by far less readable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

黑寡妇 2024-12-26 09:43:27

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

for _myvar1, myvar2 in mylist:

两全其美:

  • 没有 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:

getting the best of both worlds:

  • no Pylint warning,
  • and information about the record structure

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.

£烟消云散 2024-12-26 09:43:27

您尝试过其中任何一个吗?

for _, myvar in mylist:
    #Do stuff

在 Python 中工作得很好并且相对地道。

Did you try either of these?

for _, myvar in mylist:
    #Do stuff

works fine in Python and is relatively idiomatic.

半山落雨半山空 2024-12-26 09:43:27

当我想强调只使用 myvar2 时,我会写 for _, myvar2 in mylist

当我想提醒读者(通常是我)记录结构是什么时,我会写 for myvar1, myvar2 in mylist

_ 名称只是一次性值的命名约定。 CPython 解释器为它进行变量赋值,就像对任何其他变量名进行赋值一样(幸运的是,*STORE_FAST* 是一个非常便宜的操作)。相比之下,PyPy 解释器 会将未使用的变量赋值识别为死代码,因此无论如何,您都可以免费获得优化你写吧。

如果您对 CPython 如何解释您的代码感到好奇,dis 模块可以提供有用的见解:

>>> from dis import dis
>>> def f(lot):
        for _, var2 in lot:
            print var2


>>> dis(f)
  2           0 SETUP_LOOP              25 (to 28)
              3 LOAD_FAST                0 (lot)
              6 GET_ITER            
        >>    7 FOR_ITER                17 (to 27)
             10 UNPACK_SEQUENCE          2
             13 STORE_FAST               1 (_)
             16 STORE_FAST               2 (var2)

  3          19 LOAD_FAST                2 (var2)
             22 PRINT_ITEM          
             23 PRINT_NEWLINE       
             24 JUMP_ABSOLUTE            7
        >>   27 POP_BLOCK           
        >>   28 LOAD_CONST               0 (None)
             31 RETURN_VALUE 

正如其他发帖者所提到的,来自 pylint 的警告有时可能是愚蠢的。如果您喜欢在代码中使用短变量名称,则只需忽略 pylint 投诉即可。正如 Francis Avila 指出的那样, pylint 不应该在这种情况下抱怨 _

I write for _, myvar2 in mylist when I want to emphasize that only myvar2 is used.

And I write for myvar1, myvar2 in mylist when I want to remind the reader (usually me) what the record structure is.

The _ name is just a naming convention for a throw-away value. The CPython interpreter makes the variable assignment for it just like it would with any other variable name (fortunately, *STORE_FAST* is a very cheap operation). In contrast, the PyPy interpreter will identify the unused variable assignment as dead code, so you get the optimization for free regardless of how you write it.

If you're curious about how CPython interprets your code, the dis module can provide useful insights:

>>> from dis import dis
>>> def f(lot):
        for _, var2 in lot:
            print var2


>>> dis(f)
  2           0 SETUP_LOOP              25 (to 28)
              3 LOAD_FAST                0 (lot)
              6 GET_ITER            
        >>    7 FOR_ITER                17 (to 27)
             10 UNPACK_SEQUENCE          2
             13 STORE_FAST               1 (_)
             16 STORE_FAST               2 (var2)

  3          19 LOAD_FAST                2 (var2)
             22 PRINT_ITEM          
             23 PRINT_NEWLINE       
             24 JUMP_ABSOLUTE            7
        >>   27 POP_BLOCK           
        >>   28 LOAD_CONST               0 (None)
             31 RETURN_VALUE 

As the other posters have mentioned, the warnings from pylint can sometimes be inane. If you prefer a short variable name in your code, then just ignore the pylint complaint. As Francis Avila pointed out, pylint should't complain about _ in this context.

三人与歌 2024-12-26 09:43:27

我想你可以这样做:

for myvar in (t[1] for t in mylist):
    pass

但坦率地说,我认为你应该忽略这种情况下的 pylint 警告 - 它足够漂亮,不会引起任何混乱(这就是为什么你首先想要美丽)。

I suppose you could do this:

for myvar in (t[1] for t in mylist):
    pass

But frankly I think you should just ignore the pylint warning in this case--it's beautiful enough and won't cause any confusion (which is why you want to beauty in the first place).

拒绝两难 2024-12-26 09:43:27

我想说 Python 就是编写可读代码 - 任何“美感”都只是副作用。

元组的第一项可以像这样删除:

for myvar2 in zip(*mylist)[1]:
    # Do stuff with myvar2

但我不确定我是否真的会推荐它。就我个人而言,我只会使用:

for myvar1, myvar2 in mylist:
    # Do stuff with myvar2

...并忽略 pylint。

I would say Python is all about writing readable code - any "beauty" is merely a side-effect.

The first item of the tuple could be eliminated like this:

for myvar2 in zip(*mylist)[1]:
    # Do stuff with myvar2

But I'm not sure I'd really recommend it. Personally I would just use:

for myvar1, myvar2 in mylist:
    # Do stuff with myvar2

... and ignore pylint.

走过海棠暮 2024-12-26 09:43:27
tu = [(12,'sea'),(478,'badada'),(789,'zut')]

for x,x in tu:
    print x

结果

sea
badada
zut

tu = [(12,'sea'),(478,'badada'),(789,'zut')]

for x,x in tu:
    print x

result

sea
badada
zut

!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文