Списъци, n-торки,
множества, речници

„ Програмиране с Python“, ФМИ

01.03.2010г.

Още малко общи неща за езика

Колекции в Python

Списъци

Списъци — примери


>>> words = ["Foo", "Bar", "Baz", "Qux"]
>>> primes = [2, 3, 5, 7, 11, 13, 17, 19]
>>> asl = [21, "Male", "Sofia"]
>>> dish = ["spam", "bacon", "sausage", "spam"]

>>> actor = "Eric Idle"
>>> sketch = "Spam"
>>> stuff = [actor, 42, sketch]
>>> print(stuff)
['Eric Idle', 42, 'Spam']

>>> stuff[1] = stuff
>>> print(stuff)
['Eric Idle', [...], 'spam']
>>> stuff[1][0] = 2 ** 9
>>> print(stuff)
[512, [...], 'Spam']

Списъци — основни операции

Списъци — индексиране и отрязъци

>>> cheese = ['Red Leicester', 'Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[0]
'Red Leicester'
>>> cheese[-1]
'Limburger'
>>> cheese[1:4]
['Cheddar', 'Emmental', 'Mozzarella']
>>> cheese[1:-1]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit']
>>> cheese[1:]
['Cheddar', 'Emmental', 'Mozzarella', 'Tilsit', 'Limburger']
>>> cheese[:3]
['Red Leicester', 'Cheddar', 'Emmental']
>>> cheese[0:6:2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::2]
['Red Leicester', 'Emmental', 'Tilsit']
>>> cheese[::-1]
['Limburger', 'Tilsit', 'Mozzarella', 'Emmental', 'Cheddar', 'Red Leicester']

Списъци — промяна

>>> food = ['eggs', 'bacon', 'spam']
>>> print(food)
['eggs', 'bacon', 'spam']
>>> food[1] = 'sausage'
>>> print(food)
['eggs', 'sausage', 'spam']
>>> food.append('spam')
>>> print(food)
['eggs', 'sausage', 'spam', 'spam']
>>> food.append(['манджа', 'грозде'])
>>> print(food)
['eggs', 'sausage', 'spam', 'spam', ['манджа', 'грозде']]

Списъци — промяна (2)


>>> food = ['ham', 'eggs']
>>> food.extend(['bacon', 'spam'])
>>> print(food)
['ham', 'eggs', 'bacon', 'spam']
>>> del food[1]
>>> print(food)
['ham', 'bacon', 'spam']
>>> food[:2] = ['I', 'want', 'more']
>>> print(food)
['I', 'want', 'more', 'spam']
>>> del food[:3]
>>> print(food)
['spam']

Списъци — методи


>>> knights = ["Arthur", "Galahad"]
>>> knights.append('Bedevere')
>>> knights
['Arthur', 'Galahad', 'Bedevere']
>>> knights.extend(['Lancelot', 'Robin']) # Може и knigts += ['Lancelot', 'Robin']
>>> knights
['Arthur', 'Galahad', 'Bedevere', 'Lancelot', 'Robin']
>>> knights.sort()
>>> knights
['Arthur', 'Bedevere', 'Galahad', 'Lancelot', 'Robin']
>>> knights.reverse()
>>> knights
['Robin', 'Lancelot', 'Galahad', 'Bedevere', 'Arthur']
>>> someone = knights.pop()
>>> print(someone, knights)
Arthur ['Robin', 'Lancelot', 'Galahad', 'Bedevere']
>>> someone = knights.pop(2)
>>> print(someone, knights)
Galahad ['Robin', 'Lancelot', 'Bedevere']

Списъци — методи (2)


>>> food = ['spam', 'eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.index('eggs')
1
>>> food.index('hamandeggs')
ValueError: list.index(x): x not in list
>>> food.index('spam', 1)
3
>>> food.index('spam', 1, 3)
ValueError: list.index(x): x not in list
>>> food.count('spam')
3
>>> food.count('bacon')
1

Списъци — методи (3)


>>> food = ['spam', 'eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.insert(2, 'spam')
>>> food
['spam', 'eggs', 'spam', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('spam')
>>> food
['eggs', 'spam', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('spam')
>>> food
['eggs', 'sausage', 'spam', 'bacon', 'spam']
>>> food.remove('zzz')
ValueError: list.remove(x): x not in list
>>> ['eggs', 'sausage'] * 3
['eggs', 'sausage', 'eggs', 'sausage', 'eggs', 'sausage']

Отново към for цикъла

Списъци — обхождане


>>> numbers = [1, 2, 3, 5, 7, 11, 13]
>>> answer = 0
>>> 
>>> for n in numbers:
        answer += n
        print("Adding {0} to the answer".format(n))
>>> print(answer)
42

Списъци — обхождане (2)

for n in range(0, 20):
    if n % 2: continue
    print(n)
    if n > 9: break
Произвежда следния резултат:
0
2
4
6
8
10

Имена и неща

В python оператора = дава ново име на съществуващ обект.

Последния не се копира.


>>> spam = ['Lancelot', 'Arthur']
>>> eggs = spam
>>> eggs[1] = 'Bedevere'
>>> spam
['Lancelot', 'Bedevere']

Нищо

В python нищото е None.


>>> print(None)
None
>>> 1 is None
False
>>> if not None:
        print('None is treated as "False"')
None is treated as "False"

n-торки (tuples)

n-торки (tuples) (2)

Аналогично на списъците поддържат:

n-торки (tuples) (3)

Сравняване на списъци/n-торки

Списъците/n-торките се сравняват лексигокрафски


>>> (1, 2) < (1, 3)
True
>>> (1, 2) < (1, 2)
False
>>> (1, 2) < (1, 2, 3)
True
>>> [1, 2] < [1, 3]
True
>>> (1, 2) < [1, 3] # tuple vs. list
TypeError: unorderable types: tuple() < list()

Множества (set)

Множества (set) - примери

>>> numbers = {1, 2, 3, 8, 2}
>>> numbers
{8, 1, 2, 3}
>>> 2 in numbers
True
>>> 4 in numbers
False
>>> numbers.add(4)
>>> 4 in numbers
True
>>> numbers.remove(1)
>>> numbers
{8, 2, 3, 4}

Множества (set) - примери (2)

>>> {1, 2, 3} | {2, 3, 4}
{1, 2, 3, 4}
>>> {1, 2, 3} & {2, 3, 4}
{2, 3}
>>> {1, 2, 3} - {2, 3, 4}
{1}
>>> {1, 2, 3} ^ {2, 3, 4}
{1, 4}
>>> {1, 2, 3} < {2, 3, 4}
False
>>> {2, 3} < {2, 3, 4} # < - подмножество
True
>>> {2, 3} == {2.0, 3}
True
>>> {1, 2}.isdisjoint({3, 4})
True

Преобразуване м/у списък, n-торка и множество

>>> set([1, 2, 3, 8, 2])
{8, 1, 2, 3}
>>> list({1, 2, 3})
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> list((1, 2, 3))
[1, 2, 3]

Речници

Речници (2)

>>> languages = {
    'Spain': 'Spanish',
    'Great Britain': 'English',
    'Italy': 'Italian',
    'Mexico': 'Spanish',
    'France': 'French',
    'USA': 'English',
}

>>> languages['Mexico']
'Spanish'

Речници (3)

>>> capitals = {
    'Germany': 'Berlin',
    'France': 'Paris',
    'Brazil': 'Rio de Janeiro',
    'Malaysia': 'Kuala Lumpur',
}
>>> capitals['Brazil']
'Rio de Janeiro'
>>> capitals['Brazil'] = 'Brazil'
>>> capitals['Brazil']
'Brazil'
>>> capitals['Sweden'] = 'Stockholm'
>>> capitals['Sweden']
'Stockholm'
>>> del capitals['Malaysia']
>>> capitals['Malaysia']
KeyError: 'Malaysia'

Речници — методи

>>> capitals = {
    'Germany': 'Berlin',
    'France': 'Paris',
    'Brazil': 'Rio de Janeiro',
    'Sweden': 'Stockholm',
}
>>> capitals.get('Assyria')
None
>>> capitals.get('Assyria', "I don't know")
"I don't know"
>>> 'Sweden' in capitals
True
>>> list(capitals.keys())
['Brazil', 'Sweden', 'Germany', 'France']
>>> list(capitals.values())
['Rio de Janeiro', 'Stockholm', 'Berlin', 'Paris']
>>> len(capitals)
4

Речници — методи (2)

>>> numbers = {
    "One": "I",
    "Two": "II",
}

>>> list(numbers.items())
[('One', 'I'), ('Two', 'II')]
>>> numbers.update({"Three": "III", "Four": "IV"})
>>> numbers
{'Four': 'IV', 'Three': 'III', 'Two': 'II', 'One': 'I'}
>>> numbers.pop('Four')
'IV'
>>> numbers
{'Three': 'III', 'Two': 'II', 'One': 'I'}

Речници — методи (3)


>>> {1: 1, 2:2} == {2: 2, 1: 1}
True
>>> numbers = {
    "One": "I",
    "Two": "II",
}

>>> numbers_copy = numbers.copy()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{'Two': 'II', 'One': 'I'}
>>> numbers.clear()
>>> numbers_copy
{'Two': 'II', 'One': 'I'}
>>> numbers
{}

Три други начина за създаване на речник

Речници — хеш функции

Речници — функция за сравняване

Още въпроси?