Распаковка

Распаковка списков в Python

 

 

 

 

 

Перейдите к следующему слайду, нажав кнопку Вправо

PATH_TO_HOME = [
    ('LEFT', 2),
    ('FORWARD', 40),
    ('RIGHT', 7),
]

for part in PATH_TO_HOME:
    direction = part[0]
    steps_count = part[1]
    print('Go to', direction, end=' ')
    print(steps_count, 'steps.'
PATH_TO_HOME = [
    ('LEFT', 2),
    ('FORWARD', 40),
    ('RIGHT', 7),
]

for direction, steps_count in PATH_TO_HOME:
    print('Go to', direction, end=' ')
    print(steps_count, 'steps.'

Было:

Стало:

Распаковка в цикле

def get_around_path():
    return [
        ('LEFT', 5),
        ('FORWARD', 5),
        ('RIGHT', 5),
    ]

PATH_TO_HOME = []

PATH_TO_HOME.append(('FORWARD', 20))
PATH_TO_HOME.extend(get_around_path())
PATH_TO_HOME.append(('FORWARD', 100))
PATH_TO_HOME.extend(get_around_path())
PATH_TO_HOME.append(('FORWARD', 10))
PATH_TO_HOME.append(('LEFT', 20))
def get_around_path():
    return [
        ('LEFT', 5),
        ('FORWARD', 5),
        ('RIGHT', 5),
    ]

PATH_TO_HOME = [
    ('FORWARD', 20),
    *get_around_path(),
    ('FORWARD', 100),
    *get_around_path(),
    ('FORWARD', 10),
    ('LEFT', 20),
]

Было:

Стало:

Распаковка внутри списка

def get_around_path():
    return [
        'LEFT', 'LEFT', 'LEFT',
        'FORWARD', 'FORWARD',
        'RIGHT', 'RIGHT', 'RIGHT',
    ]

PATH_TO_HOME = []

PATH_TO_HOME.append('LEFT')
PATH_TO_HOME.append('FORWARD')
PATH_TO_HOME.append('FORWARD')
PATH_TO_HOME.append('FORWARD')
PATH_TO_HOME.append('FORWARD')
PATH_TO_HOME.extend(get_around_path())
PATH_TO_HOME.append('FORWARD')
PATH_TO_HOME.append('FORWARD')
def get_around_path():
    return [
        *['LEFT'] * 3,
        *['FORWARD'] * 2,
        *['RIGHT'] * 3,
    ]

PATH_TO_HOME = [
    'LEFT',
    *['FORWARD'] * 4,
    *get_around_path(),
    *['FORWARD'] * 2,
]

Было:

Стало:

Распаковка + умножение списка

Распаковка в Python

By Евгений Евсеев

Распаковка в Python

  • 641

More from Евгений Евсеев