[关闭]
@jtahstu 2018-04-15T00:25:45.000000Z 字数 1726 阅读 1994

Python Cookbook - 1.1. Unpacking a Sequence into Separate Variables

python


1 Data Structures and Algorithms

Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries.For the most part, the use of these structures is straightforward. However,common questions concerning searching, sorting, ordering, and filtering often arise.Thus, the goal of this chapter is to discuss common data structures and algorithms involving data. In addition, treatment is given to the various data structures contained in the collections module.

1.1. Unpacking a Sequence into Separate Variables

Problem

You have an N-element tuple or sequence that you would like to unpack into a collection of N variables.

Solution

Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of variables and structure match the sequence.

For example:

  1. >>> p = (4, 5)
  2. >>> x, y = p
  3. >>> x
  4. 4
  5. >>> y
  6. 5
  7. >>>
  8. >>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
  9. >>> name, shares, price, date = data
  10. >>> name
  11. 1
  12. 'ACME'
  13. >>> date
  14. (2012, 12, 21)
  15. >>> name, shares, price, (year, mon, day) = data
  16. >>> name
  17. 'ACME'
  18. >>> year
  19. 2012
  20. >>> mon
  21. 12
  22. >>> day
  23. 21
  24. >>>

If there is a mismatch in the number of elements, you’ll get an error. For example:

  1. >>> p = (4, 5)
  2. >>> x, y, z = p
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. ValueError: need more than 2 values to unpack
  6. >>>

Discussion

Unpacking actually works with any object that happens to be iterable, not just tuples or
lists. This includes strings, files, iterators, and generators.

For example:

  1. >>> s = 'Hello'
  2. >>> a, b, c, d, e = s
  3. >>> a
  4. 'H'
  5. >>> b
  6. 'e'
  7. >>> e
  8. 'o'
  9. >>>

When unpacking, you may sometimes want to discard certain values. Python has no special syntax for this, but you can often just pick a throwaway variable name for it. For

example:

  1. >>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
  2. >>> _, shares, price, _ = data
  3. >>> shares
  4. 50
  5. >>> price
  6. 91.1
  7. >>>

However, make sure that the variable name you pick isn’t being used for something else
already.

Note

N1


N1

Translate

N1


N1

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注