Python Essentials
上QQ阅读APP看书,第一时间看更新

Using the head, *tail assignment

When working with sequences, there are some algorithms which work by separating the head of the sequence from the rest of the sequence. We can do this with a variation on the assignment statement. We like to call this the head, *tail = assignment statement.

Let's say that we have an input string with a list of values, something like this:

>>> line = "255  73 108 Radical Red"
>>> line.split()
['255', '73', '108', 'Radical', 'Red']

We have split the string into space-delimited words with line.split(). In this case, the head of the list is the first three fields of the red, green, and blue elements of a color. The tail is all the remaining fields, which is the name parsed into separate words.

We can use head, *tail = assignment to split the first three fields from the remaining files.

It looks like this:

>>> r, g, b, *name = line.split()
>>> g
'73'
>>> name
['Radical', 'Red']

We've assigned the first three items to three separate variables, r, g, and b. The * means that all of the remaining items will be collected into a single variable, name.

We can reconstruct the original name with the join() method, with a space as the separator string:

>>> " ".join(name)
'Radical Red'

We've used a space to join the elements of the sequence named name. This will reconstruct the original color name as a single string instead of a list of words.