简体   繁体   English

我怎样才能迭代元组的第一个变量

[英]How can I iterate over only the first variable of a tuple

In python, when you have a list of tuples, you can iterate over them. 在python中,当你有一个元组列表时,你可以迭代它们。 For example when you have 3d points then: 例如,当你有3d点时:

for x,y,z in points:
    pass
    # do something with x y or z

What if you only want to use the first variable, or the first and the third. 如果您只想使用第一个变量,或者第一个和第三个变量,该怎么办? Is there any skipping symbol in python? python中有跳过符号吗?

Is something preventing you from not touching variables that you're not interested in? 是什么阻止你不接触你不感兴趣的变量? There is a conventional use of underscore in Python to indicate variable that you're not interested. 在Python中有一个常规的下划线用来表示你不感兴趣的变量。 Eg: 例如:

for x, _,_ in points:
    print(x)

You need to understand that this is just a convention and has no bearing on performance. 您需要了解这只是一种惯例,与性能无关。

Yes, the underscore: 是的,下划线:

>>> a=(1,2,3,4)
>>> b,_,_,c = a
>>> b,c
(1, 4)

This is not exactly 'skipping', just a convention. 这不是'跳过',只是一个惯例。 Underscore variable still gets the value assigned: 下划线变量仍然获得分配的值:

>>> _
3

A common way to do this is to use underscores for the unused variables: 执行此操作的常用方法是对未使用的变量使用下划线:

for x, _, z in points:
    # use x and z

This doesn't actually do anything different from what you wrote. 这实际上与你所写的不同。 The underscore is a normal variable like any other. 下划线是一个像其他任何一样的正常变量。 But this shows people reading your code that you don't intend to use the variable. 但这表明人们在阅读您的代码时并不打算使用该变量。

It is not advisable to do this in the interactive prompt as _ has a special meaning there: the value of the last run statement/expression. 不建议在交互式提示中执行此操作,因为_在那里具有特殊含义:最后一个运行语句/表达式的值。

While this is not as slick as you're asking for, perhaps this is most legible for your intentions of giving meaningful names only to the tuple indices you care about: 虽然这并不像你要求的那样光滑,但也许这对于你只想给你关心的元组索引提供有意义的名字的意图是最清晰的:

for each in points:
    x = each[0]
    # do something with x

In Python 3.1 you can use an asterisk in front of an identifier on the left side of a tuple assignment and it will suck up whatever is left over. 在Python 3.1中,您可以在元组赋值左侧的标识符前面使用星号,它会吸收遗留的任何内容。 This construct will handle a variable number of tuple items. 此构造将处理可变数量的元组项。 Like this: 像这样:

>>> tpl = 1,2,3,4,5
>>> a, *b = tpl
>>> a
1
>>> b
>>> (2, 3, 4, 5)

Or in various orders and combinations: 或者以各种顺序和组合:

>>> a, *b, c = tpl
>>> a
1
>>> b
(2, 3, 4)
>>> c
5

So, for the case you asked about, where you're only interested in the first item, use *_ to suck up and discard the remaining items you don't care about: 因此,对于您询问的情况,您只对第一项感兴趣,请使用* _来吸收并丢弃您不关心的其余项目:

>>> a, *_ = tpl
>>> a
1

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM