Рубрики
Без рубрики

Очаровательный Python: Списки

Если учебные пособия по математике с математическими примерами являются байн вашего существования, продолжайте чтение. Эта серия использует … Помечено Python, начинающим.

Если учебные пособия по математике с математическими примерами являются байн вашего существования, продолжайте чтение. Эта серия использует относительные примеры, такие как собаки и кошки.

Списки

Список – это коллекция, которая заказывается и изменчиво, и могут быть дублирующими элементы.

Создание списка

# creating a list with a builtin function
list_name = list('list item 1', 'list item 2', 'list item 3')

# creating a list with brackets
another_list_name = ['list item 1', 'list item 2', 'list item 3']

# you can create an empty list like this
list = []

Доступ к элементам списка с использованием индексации

0 1 5 4 2 3
-6 -5 -1 -2 -4 -3
things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']

print(things[0])
>>>cat

print(things[-2])
>>>lemon

Изменение списков

Списки измеряются или модифицируются.

Добавить через индекс

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things[0] = 'chair' # adds 'chair' to the beginning of list, at index 0
print(things)  # returns newly modified list
>>>['chair', 'cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']

Добавить к концу

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things.append = 'chair' # adds 'chair' to the end of list
print(things)  # returns newly modified list
>>>['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road', 'chair']

Проверять

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
does_exist = 'banana' in things  # sees if 'banana' is in the list
print(does_exist)
>>>True
does_exist = 'lime' in things  # sees if 'lime' is in the list
print(does_exist)
>>>False

Вставлять

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things.insert('pie', 1)  # adds 'pie' at index 1
print(things)
>>>'cat', 'pie', 'dog', 'mouse', 'cheese', 'lemon', 'road'

Удалять

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things.remove('mouse')  # removes 'mouse', regardless of index
print(things)
>>>'cat', 'dog', 'cheese', 'lemon', 'road'

Поп

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things.pop(-2)  # removes item referenced by index
print(things)
>>>'cat', 'dog', 'mouse', 'cheese', 'road'

Удалить

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
del things[0]  # deletes item referenced by index
print(things)
>>>'dog', 'mouse', 'cheese', 'lemon', 'road'

Прозрачный

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']  # our list
things.clear()
print(things)  # nothing will show because you've cleared all items from the list
>>>

Присоединение

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']
more_things = ["table", "book", "blanket"]
new_list = things + more_things  # combines both lists in the order written
print(new_list)
>>>'cat', 'dog', 'mouse', 'cheese', 'lemon', 'road', "table", "book", "blanket"

newer_list = more_things + things
print(newer_list)
>>>"table", "book", "blanket", 'cat', 'dog', 'mouse', 'cheese', 'lemon', 'road'

Подсчет

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']
print(things.count())
>>>6

Реверсив

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']

things.reverse()  # flip the order of the list
print(things)
>>>'road', 'lemon', 'cheese', 'mouse', 'dog', 'cat'

Сортировка

things = ['cat', 'dog', 'mouse', 'cheese', 'lemon', 'road']

things.sort()  # alphanumeric order
print(things)
>>>'cat', 'cheese', 'dog', 'lemon', 'mouse', 'road'

things.sort(reverse=True)  # backwards
print(things)
>>>'road', 'mouse', 'lemon', 'dog', 'cheese', 'cat'

Серия на основе

30 дней Python Challenge

Asabeneh · 20 ноября 1919 · 1 мин читать

Оригинал: “https://dev.to/vickilanger/charming-the-python-lists-3eh2”