Wizualizacja danych
- Wykład 4

Lista jako stos

stack = [3, 4, 5, 8, 9]
stack.append(6)
stack.append(7)
print(stack)
print(stack.pop())
print(stack)
[3, 4, 5, 8, 9, 6, 7]
7
[3, 4, 5, 8, 9, 6]

Lista jako kolejka

from collections import deque

queue = deque(["aw", "tg", "kj"])
queue.append("gg")
print(queue)
print(queue.popleft())
print(queue)
deque(['aw', 'tg', 'kj', 'gg'])
aw
deque(['tg', 'kj', 'gg'])

List Comprehensions

squares = []
for x in range(5):
    squares.append(x ** 2)

print(squares)
[0, 1, 4, 9, 16]
squares = [x**2 for x in range(5)]
print(squares)
[0, 1, 4, 9, 16]

Krotka - tuple

krotka = 123, 'abc', True
krotka2 = (123, 'abc', True)
print(krotka[2])
True
krotka[0] = 1

TypeError: ‘tuple’ object does not support item assignment

https://docs.python.org/3.10/library/stdtypes.html#tuple

Zbiór - set

cyfry = {'raz', 'dwa', 'raz', 'trzy', 'raz', 'osiem'}
print(cyfry)
{'dwa', 'trzy', 'osiem', 'raz'}

https://docs.python.org/3.10/library/stdtypes.html#set

x = {2, 3, 4, -3, 5, 2}
y = {5, 6, 7}
z = {'a', 'b'}
w = {3, 4}
print(x)
print(len(x))
print(0 in x)
print(0 not in x)
{2, 3, 4, 5, -3}
5
False
True
x = {2, 3, 4, -3, 5, 2}
y = {5, 6, 7}
z = {'a', 'b'}
w = {3, 4}
print(x.isdisjoint(y))
print(x.isdisjoint(z))
print(w.issubset(x))
print(x.issubset(w))
print(w <= x)
print(w < x)
print(w.issuperset(x))
print(x.issuperset(w))
print(w >= x)
print(w > x)
False
True
True
False
True
True
False
True
False
False
x = {2, 3, 4, -3, 5, 2}
y = {5, 6, 7}
z = {'a', 'b'}
w = {3, 4}
print(x.union(y))
print(x | y)
print(x.intersection(y))
print(x & y)
print(x.difference(y))
print(x - y)
print(x.symmetric_difference(y))
print(x ^ y)
print(x.copy())  # płytka kopia
{2, 3, 4, 5, 6, 7, -3}
{2, 3, 4, 5, 6, 7, -3}
{5}
{5}
{2, 3, 4, -3}
{2, 3, 4, -3}
{2, 3, 4, 6, 7, -3}
{2, 3, 4, 6, 7, -3}
{2, 3, 4, 5, -3}

x = {2, 3, 4, -3, 5, 2}
x.update({11})
print(x)
x |= {12}
print(x)
x = {2, 3, 4, -3, 5, 2}
x.intersection_update({5})
print(x)
x = {2, 3, 4, -3, 5, 2}
x &= {5}
print(x)
x = {2, 3, 4, -3, 5, 2}
{2, 3, 4, 5, 11, -3}
{2, 3, 4, 5, 11, 12, -3}
{5}
{5}

x = {2, 3, 4, -3, 5, 2}
x.difference_update({4})
print(x)
x = {2, 3, 4, -3, 5, 2}
x -= {4}
print(x)
x = {2, 3, 4, -3, 5, 2}
x.symmetric_difference_update({4, 11})
print(x)
x = {2, 3, 4, -3, 5, 2}
x ^= {4, 11}
print(x)
{2, 3, 5, -3}
{2, 3, 5, -3}
{2, 3, 5, 11, -3}
{2, 3, 5, 11, -3}
x = {2, 3, 4, -3, 5, 2}
print(x)
x.add(11)
print(x)
x.remove(-3)  # usuwa gdy jest, inaczej KeyError
print(x)
x.discard(12)
print(x)
{2, 3, 4, 5, -3}
{2, 3, 4, 5, 11, -3}
{2, 3, 4, 5, 11}
{2, 3, 4, 5, 11}
x = {2, 3, 4, -3, 5, 2}
print(x)
x.discard(2)
print(x)
x = {2, 3, 4, -3, 5, 2}
print(x.pop())
print(x)
x.clear()
print(x)
{2, 3, 4, 5, -3}
{3, 4, 5, -3}
2
{3, 4, 5, -3}
set()

Słownik

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
tel['jack']
del tel['sape']
tel['irv'] = 4127
print(tel)
{'jack': 4098, 'sape': 4139, 'guido': 4127}
{'jack': 4098, 'guido': 4127, 'irv': 4127}

https://docs.python.org/3.10/library/stdtypes.html#mapping-types-dict

d = {"one": 1, "two": 2, "three": 3, "four": 4}
print(d)
print(list(d))
print(list(d.values()))
d["one"] = 42
print(d)
del d["two"]
print(d)
d["two"] = None
print(d)
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
['one', 'two', 'three', 'four']
[1, 2, 3, 4]
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
{'one': 42, 'three': 3, 'four': 4}
{'one': 42, 'three': 3, 'four': 4, 'two': None}
d = {"one": 1, "two": 2, "three": 3, "four": 4}
print(d)
print(list(reversed(d)))
print(list(reversed(d.values())))
print(list(reversed(d.items())))
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
['four', 'three', 'two', 'one']
[4, 3, 2, 1]
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
d = {"one": 1, "two": 2, "three": 3, "four": 4}
print("one" in d)
print(1 in d)
print("one" not in d)
print(1 not in d)
print(iter(d))
for elem in iter(d):
    print(elem)
True
False
False
True
<dict_keyiterator object at 0x000001DD3E81B600>
one
two
three
four
d = {"one": 1, "two": 2, "three": 3, "four": 4}
d.clear()
print(d)
d = {"one": 1, "two": 2, "three": 3, "four": 4}
e = d.copy() # płyta kopia
print(e)
{}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
x = ('key1', 'key2', 'key3')
y = 0
d1 = dict.fromkeys(x, y)
print(d1)
z = (3, 4, 5)
d2 = dict.fromkeys(x, z)
print(d2)
{'key1': 0, 'key2': 0, 'key3': 0}
{'key1': (3, 4, 5), 'key2': (3, 4, 5), 'key3': (3, 4, 5)}
d = {"one": 1, "two": 2, "three": 3, "four": 4}
print(d.get("two"))
print(d.items())
print(d.keys())
print(d.pop("three"))
print(d)
print(d.popitem())
print(d)
2
dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
dict_keys(['one', 'two', 'three', 'four'])
3
{'one': 1, 'two': 2, 'four': 4}
('four', 4)
{'one': 1, 'two': 2}
d = {"one": 1, "two": 2, "three": 3, "four": 4}
d.update(red=1, blue=2)
print(d)
print(d.values())
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'red': 1, 'blue': 2}
dict_values([1, 2, 3, 4, 1, 2])
d = {"one": 1, "two": 2, "three": 3, "four": 4}
d2 = {"a": 11, "b": 12}
d3 = d | d2
print(d3)
print(d)
d |= d2
print(d)
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'a': 11, 'b': 12}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'a': 11, 'b': 12}

Python comprehension

a = [3, 4, 5]
print(a)
a2 = [i**2 for i in a]
print(a2)
a3 = {i**2 for i in a}
print(a3)
a4 = {i: i**2 for i in a}
print(a4)
[3, 4, 5]
[9, 16, 25]
{16, 9, 25}
{3: 9, 4: 16, 5: 25}
a = [3, 4, 5]
print(a)
a2 = (i**2 for i in a)
print(a2)
for i in a2:
    print(i)
[3, 4, 5]
<generator object <genexpr> at 0x000001DD3E84C350>
9
16
25
a = [3, 4, "w", 5]
print(a)
w = [i*i for i in a if isinstance(i, int)]
print(w)
[3, 4, 'w', 5]
[9, 16, 25]
a = [3, 4, "w", 5]
print(a)
w = [i*i if isinstance(i, int) else i for i in a]
print(w)
[3, 4, 'w', 5]
[9, 16, 'w', 25]

Napisy

  • trochę podobne do listy
  • typ sekwencyjny do przechowywania znaków, ale w odróżnieniu od listy jest niezmienny
  • w języku Python nie ma oddzielnego typu znakowego
  • apostrofy i cudzysłów można stosować zamiennie, ale konsekwentnie

Inne nazwy: - string, napisy, łańcuchy znaków

Abstrakcyjnie:

  • na końcu każdego napisu jest znak “zerowy” - będzie widać lepiej w C/C++

Tablica znaków ASCII https://upload.wikimedia.org/wikipedia/commons/5/5c/ASCII-Table-wide.pdf

a = "Olsztyn"
print(a)
print(a[3])
#a[2] = 'w'
Olsztyn
z
a = "Olsztyn"
b = "Gdańsk"
print(a + b)
print(a * 2)
print(2 * a)
OlsztynGdańsk
OlsztynOlsztyn
OlsztynOlsztyn

Specjalne funkcje

  • chr() zamienia liczbę całkowitą na znak
  • ord() zamienia znak na liczbę całkowitą odpowiadającą pozycji w tabeli znaków
  • len() - długość napisu
  • str() - rzutuje argument na napis

Porządek leksykograficzny

Mądra definicja z wikipedii:

Relację leksykograficzną \(\preccurlyeq\) między ciągami \(\alpha, \beta \in X^*\) ustala się następująco:

  • jeśli istnieje wskaźnik \(j\) taki, że \(\alpha(j) \neq \beta(j),\) to znajdujemy najmniejszy \(i\) o tej własności. Wówczas

    • \(\alpha \preccurlyeq \beta\) gdy \(\alpha(i) \preccurlyeq \beta(i)\) lub \(\beta \preccurlyeq \alpha\) gdy \(\beta(i) \preccurlyeq \alpha(i)\) (tzn. relacja między ciągami jest zgodna z relacją między odpowiednimi elementami)
  • jeśli taki \(j\) nie istnieje, to

    • jeśli oba są skończone i tej samej długości, to \(\alpha = \beta\)
    • jeśli oba ciągi są nieskończone, to \(\alpha = \beta\)
    • jeśli są różnej długość np. \(\beta\) jest dłuższy od \(\alpha\) (w szczególności \(\beta\) może być nieskończony), to \(\alpha\ \preccurlyeq\ \beta\)

Przykłady:

print("A" < "a")
print("Abc" < "aTw")
print("vccx" < "123")
print("ABC" < "AB")
print("AB" < "ABC")
True
True
False
False
True

Fomatowanie napisów

  • trzy różne konwencje
  • niektóre rzeczy nie działają w każdej wersji 3.x
  • warto zastanowić się czy warto używać tych konstrukcji? czasem może lepiej skorzystać z funkcji print?

styl printf

Zaczerpnięty z języka C - stare.

https://docs.python.org/3.10/library/stdtypes.html#old-string-formatting

a = "abc"
str = "a to %s" % a
print(str)
b = 4
c = 5
str2 = "%d + %d = %d" % (b, c, b + c)
print(str2)
a to abc
4 + 5 = 9

Dodatkowe:

https://gist.github.com/pjastr/02d01dba3d5f5c3e60ed74cb32c913ed https://gist.github.com/pjastr/cbe8418eb4798b92d7fcba4f48d32845 https://gist.github.com/pjastr/e7d5fcbebd578c1df122d307e0051707 https://gist.github.com/pjastr/00c1df223918f975d678d8455b4f5b0a

styl format

https://docs.python.org/3.10/library/string.html#formatstrings

a = "abc"
str = "a to {}".format(a)
print(str)
b = 4.2
c = 5
str2 = "{0} + {1} = {2}".format(b, c, b + c)
print(str2)
a to abc
4.2 + 5 = 9.2
b = 4.2
c = 5
str2 = "{0:f} + {1:d} = {2:e}".format(b, c, b + c)
print(str2)
4.200000 + 5 = 9.200000e+00

https://pyformat.info/

https://gist.github.com/pjastr/27fe6c13cd8bcba63be561a05af030a0

https://gist.github.com/pjastr/d40fe6eaf21a9595bcf6b43e7b020fbd

https://gist.github.com/pjastr/8a630b4a575e6a389a7dc3c5e8dc65a0

https://gist.github.com/pjastr/d42d937c7b00b80b5dfe309b4ac0e854

https://gist.github.com/pjastr/dbc9a0c1e8bf612b68e0bc7789daf53b

https://gist.github.com/pjastr/adfd7371dcbe4e4034bfb12dcfe30129

https://gist.github.com/pjastr/2980fb68a484dcb5ff595774eec4195c

Dodatkowe przykłady:

https://docs.python.org/3.9/library/string.html#format-examples https://gist.github.com/pjastr/d42d937c7b00b80b5dfe309b4ac0e854 https://gist.github.com/pjastr/90f1accf7f54d8c74ac036d59a24a9dd https://gist.github.com/pjastr/adfd7371dcbe4e4034bfb12dcfe30129 https://gist.github.com/pjastr/2980fb68a484dcb5ff595774eec4195c

f-Strings

https://docs.python.org/3.10/reference/lexical_analysis.html#f-strings

a = "abc"
str = f"a to {a}"
print(str)
b = 4.2
c = 5
str2 = f"{b} + {c} = {b+c}"
print(str2)
a to abc
4.2 + 5 = 9.2
b = 4.2
c = 5
str2 = f"{b:f} + {c:d} = {b+c:e}"
print(str2)
4.200000 + 5 = 9.200000e+00

Dodatkowe

Bibliografia