Resolvendo o ValueError: Usando o Operador Asterisco
Às vezes, você pode querer desempacotar os primeiros elementos de um iterável e coletar o restante em uma única lista. O operador asterisco (*), também conhecido como operador "estrela" ou "desempacotamento" (unpacking), é perfeito para isso. Ele permite que você atribua os elementos restantes de um iterável a uma única variável como uma lista.
Vamos criar um novo arquivo Python chamado unpack_solution2.py no diretório ~/project usando o editor WebIDE.
Adicione o seguinte código a unpack_solution2.py:
## Example 1: Unpacking the first element and collecting the rest
data1 = [10, 20, 30, 40, 50]
## Assign the first element to 'first' and the rest to 'rest_of_data'
first, *rest_of_data = data1
print(f"Example 1: first={first}, rest_of_data={rest_of_data}")
## Example 2: Unpacking the first two elements and collecting the rest
data2 = ('a', 'b', 'c', 'd')
## Assign the first two elements to 'item1' and 'item2', and the rest to 'remaining_items'
item1, item2, *remaining_items = data2
print(f"Example 2: item1={item1}, item2={item2}, remaining_items={remaining_items}")
## Example 3: Unpacking the last element and collecting the rest
data3 = [1, 2, 3, 4, 5]
## Assign the last element to 'last' and the rest to 'all_but_last'
*all_but_last, last = data3
print(f"Example 3: all_but_last={all_but_last}, last={last}")
## Example 4: Unpacking the first and last elements and collecting the middle
data4 = "python"
## Assign the first char to 'start', the last to 'end', and the middle to 'middle'
start, *middle, end = data4
print(f"Example 4: start={start}, middle={middle}, end={end}")
Salve o arquivo.
Execute o script do terminal:
python unpack_solution2.py
Você deve ver a seguinte saída:
Example 1: first=10, rest_of_data=[20, 30, 40, 50]
Example 2: item1=a, item2=b, remaining_items=['c', 'd']
Example 3: all_but_last=[1, 2, 3, 4], last=5
Example 4: start=p, middle=['y', 't', 'h', 'o'], end=n
O operador asterisco fornece uma maneira flexível de lidar com o desempacotamento quando o número de elementos no iterável pode ser maior que o número de variáveis explicitamente nomeadas. A variável prefixada com * sempre receberá uma lista dos itens restantes (que pode ser uma lista vazia se não houver itens restantes).