官术网_书友最值得收藏!

  • Python Essentials
  • Steven F. Lott
  • 247字
  • 2021-07-16 13:53:12

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.

主站蜘蛛池模板: 会宁县| 布尔津县| 乐昌市| 镇坪县| 鄂州市| 罗山县| 达尔| 清镇市| 红安县| 桦川县| 博湖县| 万盛区| 兴山县| 宁河县| 水富县| 嵊州市| 隆林| 理塘县| 文水县| 开原市| 台湾省| 浏阳市| 伊金霍洛旗| 玛多县| 丹阳市| 潜江市| 盈江县| 大厂| 济阳县| 云安县| 温泉县| 鄯善县| 屏东市| 屯留县| 余庆县| 海兴县| 汽车| 兰西县| 滨海县| 安国市| 伊金霍洛旗|