简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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