How can I iterate over only the first variable of

2020-07-10 08:42发布

问题:

In python, when you have a list of tuples, you can iterate over them. For example when you have 3d points then:

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?

回答1:

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. E.g.:

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

You need to understand that this is just a convention and has no bearing on performance.



回答2:

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


回答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.



回答4:

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


回答5:

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. 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