A comprehension egy olyan nyelvi elem a Pythonban, amely szekvenciák tömör megadását teszi lehetővé.
A comprehension némileg hasonlít a matematikában alkalmazott, tulajdonság alapján történő halmazmegadásra
Ez a szerkezet úgy néz ki, hogy egy kifejezés és mögötte a for-os kifejezés.
## Feltétel nélküli comprehension
# Állítsuk elő az első 10 négyzetszám listáját gyűjtőváltozó használatával!
print('-------00 LIST lista--------')
l = []
for i in range(1, 11):
l.append(i**2)
print(l)
print('------1---------')
# Ugyanez tömörebben, lista comprehension-nel:
l = [i**2 for i in range(1, 11)]
print(l)
print('-------11 SET halmaz--------')
# Állítsuk el® az els® 10 négyzetszám halmazát gy¶jt®változó használatával!
s = set()
for i in range(1, 11):
s.add(i**2)
print(s)
print('------2---------')
# Ugyanez tömörebben, halmaz comprehension-nel:
s = {i**2 for i in range(1, 11)}
print(s)
print('-------22 DIR szótár--------')
# Állítsunk el® egy szótárat, amely az angol kisbetús magánhangzókhoz
# hozzárendeli az ASCII-kódjukat! Használjunk gyűjtőváltozót!
d = {}
for ch in 'aeiou':
d[ch] = ord(ch)
print(d)
print('------3---------')
# Ugyanez tömörebben, szótár comprehension-nel:
d = {ch: ord(ch) for ch in 'aeiou'}
print(d)
print('-------33--------')
-------00 LIST lista-------- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ------1--------- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] -------11 SET halmaz-------- {64, 1, 4, 36, 100, 9, 16, 49, 81, 25} ------2--------- {64, 1, 4, 36, 100, 9, 16, 49, 81, 25} -------22 DIR szótár-------- {'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117} ------3--------- {'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117} -------33--------
Feltételes comprehension.
# Feltételes lista comprehension.
print([i**2 for i in range(1, 11) if i % 2 == 0])
print('-------1--------')
# Feltételes halmaz comprehension.
print({i**2 for i in range(1, 11) if i % 2 == 0})
print('-------2--------')
# Feltételes szótár comprehension.
print({ch: ord(ch) for ch in 'aeiou' if ch != 'u'})
[4, 16, 36, 64, 100] -------1-------- {64, 100, 4, 36, 16} -------2-------- {'a': 97, 'e': 101, 'i': 105, 'o': 111}
list1 = [i**2 for i in range(1,11)]
print(list1)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
list2 = [i**2 for i in range (20) if i % 2 ==0 ]
print(list2)
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
import glob, os
filenames = [os.path.basename(fname)[5:16] for fname in glob.glob("*.ipynb")]
print (sorted(set(filenames)))
[' ( ).ipynb', ' ).ipynb', ' Function.i', ' _method.ip', '.ipynb', 'Nets_Cifar_', '_CIFAR10_Ea', '_ConvNet_So', '_Intro_to_M', '_MNIST_Eage', '_Pre_Made_E', '_interakcio', '_regexp.ipy', '_sheet04.ip', 'a func.ipyn', 'act.ipynb', 'at04.ipynb', 'der.ipynb', 'ehension.ip', 'ergy_minimi', 'ex Number.i', 'g.ipynb', 'gex.ipynb', 'ial-1st-exp', 'ial-pipelin', 'ikit.ipynb', 'ions Exampl', 'ipynb', 'j.ipynb', 'lassificati', 'm.ipynb', 'mpy_perform', 'ntroduction', 'otlib.ipynb', 'pelda00.ipy', 'pelda01.ipy', 'pelda02.ipy', 'pelda03.ipy', 'pelda04.ipy', 'pelda05.ipy', 'pelda06.ipy', 'pelda07.ipy', 'pelda08.ipy', 'pelda09.ipy', 'pelda10.ipy', 'ples.ipynb', 'ptron.ipynb', 'r.ipynb', 'rial.ipynb', 'ring.ipynb', 's.ipynb', 'spy.ipynb', 'ssion-autom', 'tional Stat', 'tions handi', 'y.ipynb', 'ynb']
li = ['Afridi',4,0,2]
set1 = {i for i in li }
print(set1)
{0, 2, 'Afridi', 4}
li2 = ['Afridi','Khan']
set2 = {i for i in li2 if len(i) > 1}
print(set2)
{'Afridi', 'Khan'}
import glob, os
filenames = set(os.path.basename(fname)[5:16] for fname in glob.glob("*.ipynb"))
print (sorted(filenames))
[' ( ).ipynb', ' ).ipynb', ' Function.i', ' _method.ip', '.ipynb', 'Nets_Cifar_', '_CIFAR10_Ea', '_ConvNet_So', '_Intro_to_M', '_MNIST_Eage', '_Pre_Made_E', '_interakcio', '_regexp.ipy', '_sheet04.ip', 'a func.ipyn', 'act.ipynb', 'at04.ipynb', 'der.ipynb', 'ehension.ip', 'ergy_minimi', 'ex Number.i', 'g.ipynb', 'gex.ipynb', 'ial-1st-exp', 'ial-pipelin', 'ikit.ipynb', 'ions Exampl', 'ipynb', 'j.ipynb', 'lassificati', 'm.ipynb', 'mpy_perform', 'ntroduction', 'otlib.ipynb', 'pelda00.ipy', 'pelda01.ipy', 'pelda02.ipy', 'pelda03.ipy', 'pelda04.ipy', 'pelda05.ipy', 'pelda06.ipy', 'pelda07.ipy', 'pelda08.ipy', 'pelda09.ipy', 'pelda10.ipy', 'ples.ipynb', 'ptron.ipynb', 'r.ipynb', 'rial.ipynb', 'ring.ipynb', 's.ipynb', 'spy.ipynb', 'ssion-autom', 'tional Stat', 'tions handi', 'y.ipynb', 'ynb']
d = {i : chr(i) for i in range(65,90)}
print(d)
{65: 'A', 66: 'B', 67: 'C', 68: 'D', 69: 'E', 70: 'F', 71: 'G', 72: 'H', 73: 'I', 74: 'J', 75: 'K', 76: 'L', 77: 'M', 78: 'N', 79: 'O', 80: 'P', 81: 'Q', 82: 'R', 83: 'S', 84: 'T', 85: 'U', 86: 'V', 87: 'W', 88: 'X', 89: 'Y'}
d = {i : i**2 for i in range(1,11)}
print(d)
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20}
A matplotlib pythonban megírt mátrix kezelő modul, függvényeinek funkciói nagyban megegyeznek a MatLab-ban korábban megismert függvényekkel.
A matplotlib-et modulként kell importálni a python gyökérkönyvtárból a következő módon:
import matplotlib
Lehetőségünk van a modulokon belüli funkciók önálló használatának megkönnyítésére, a következő példában a pyplot függvényhez tudunk rövidített definíció szerű nevet készíteni:
import matplotlib.pyplot as plt
A numpy a matplotlib szerves részét képezi, mivel e modul nélkül a python stringjeit nem lehetne, vagy csak igen nehéz erőfeszítések mellett a matplotlib számára értelmezhető formátumra alakítani.
A matplotlib számára értelmezhető formátumot a következő képpen tudjuk elérni:
e = np.fromstring(var, dtype=float, sep=',')
A „fromstring” függvénynek három fő argumentuma van:
„var” -a kívánt változó sztring, amit numpy formátumúvá szeretnénk alakítani
„dtype” -a formázás után kívánt adattípus
„sep” -az átalakítandó sztringben lévő számok közötti szeparátor karakter
Igen gyakran előfordul, hogy bizonyos adatokat újra föl szeretnénk használni a későbbiekben, azonban globális változókban való tárolásuk igen bonyolult problémákat vethet fel, ezeknek a problémák kezelésére nyújthat igen nagy segítséget a ’numpy’ file illetve adatkezelő függvényei.
Numpy adatformátumú változó mentése ’npy’ formátumú file-ba
np.save("wf_hp.npy", z)
Numpy adatformátumú változó visszahívása ’npy’ formátumú file-ból
z = np.load("wf_hp.npy")
Az első mentésnél létrehozza az ‘np.save’ művelet a ‘wf_hp.npy’ file-t.
Ez a Class tartalmazza a legfontosabb grafikai függvényeket a matplotlib-ben. Ezeknek a függvényeknek a funkciói nagyban megegyeznek a MatLab-ban már korábban megismert függvények paramétereivel.
Ez a legegyszerűbb virtuális megjelenítés, ennél a függvénynél összesen kettő bemeneti változó van.
import matplotlib.pyplot as plt
#use the pyplot this name
x = np.fromstring(freq, dtype=float, sep=',') y = np.fromstring(trac, dtype=float, sep=',')
plt.figure(1) #ploting only an empty picture plt.plot(x, y) #plot the x <> y diagram plt.ion() #enable to refresh the chart plt.show() #show the figure 1 with the x <> y plot
Kitétel: az x és y numpy tömb elemeinek számának meg kell egyeznie!
Ez a függvény több rekordból álló numpy tömböt képes megjeleníteni, igen egyszerűen alkalmazható spektrum monitoring rendszereknél úgynevezett waterfall diagramm készítésére.
x = np.fromstring(freq, dtype=float, sep=',') y = np.fromstring(freq1, dtype=float, sep=',') z = np.vstack((x, y)) #concetanate the x and y to a numpy format block
plt.imshow(Z, cmap='jet') #the Z is an numpy format block plt.ion() plt.show()
Kitétel: a z numpy tömb különböző sorainak elemszámának egyenlőnek kell lennie a másik rekord elemszámával!
from matplotlib.pyplot import plot
plot([0,1,0,1])
[<matplotlib.lines.Line2D at 0x7f91dc35f128>]
import numpy as np # Matematikai számításokhoz használt függvények és adatstruktúrák a numpy modulból
import matplotlib.pyplot as plt # Ábrák készítéséhez használható függvények
%matplotlib nbagg
# ne külön ablakba rajzolja ki (ha hibát ír ki akkor 'nbagg' helyett 'inline' vagy 'notebook' szót írni)
x = np.arange(100)
print ('x alakja:', x.shape) # Így irhatunk ki dolgokat a képernyőre
w = np.random.rand(100)
print ('w alakja: ', w.shape)
plt.figure()
plt.plot(x, w) ## megjelenítés
x alakja: (100,) w alakja: (100,)
[<matplotlib.lines.Line2D at 0x20e6b3f50c8>]
## A számok összege és a becsült várhatóérték kirajzolása egy ábrára subplotok használatával:
plt.figure()
plt.subplot(121)
plt.plot(x+1, w.cumsum())
plt.subplot(122)
plt.plot(x+1, w.cumsum() / (x+1))
plt.tight_layout()
## A becsült szórás függése a mintaszámtól:
plt.plot(np.sqrt(np.cumsum((w-0.5)**2) / (x+1)))
[<matplotlib.lines.Line2D at 0x20e7db93b48>]
## Hisztogram készítése:
plt.figure()
(n, bins, patches) = plt.hist(w, bins=30, normed=True)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead. after removing the cwd from sys.path.
## Minta generálása normális eloszlásból:
w2 = np.random.normal(0, 1, size=10000)
plt.figure()
(n, bins, patches) = plt.hist(w2, bins=30, normed=True)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
A normális eloszlás sűrűségfüggvényét is rá akarjuk rajzolni a hisztogramra.
A sűrűségfüggvény képlete:
$ \mathcal{N}(x | \mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \mathrm{e}^{ \frac{ -(x-\mu)^2}{2 \sigma^2} } $
Ehhez definiálunk egy normal_pdf nevű python-függvényt, ami visszaadja minden bemenethez a sűrűségfüggvény értékét:
def normal_pdf(x, mu, sigma):
return 1./np.sqrt(2 * np.pi * sigma**2) * np.exp(-(x-mu)**2 / (2*sigma**2))
x2 = np.arange(-10, 10, 0.1) # Létrehozunk egy változót a kiszámolandó helyekkel
y = normal_pdf(x2, mu=0., sigma=1.) # Itt számoljuk ki a sűrűségfüggvény értékét minden x2 helyen
plt.figure()
(n, bins, patches) = plt.hist(w2, bins=30, normed=True, alpha=0.5)
plt.plot(x2, y, 'r-', linewidth=2.)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead. if __name__ == '__main__':
[<matplotlib.lines.Line2D at 0x20e7e5b5048>]
## Több minta generálása uniform eloszlásból:
w4 = np.random.random(10000)
plt.figure()
(n, bins, patches) = plt.hist(w4, bins=30, normed=True)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
## Két uniform eloszlású valószínűségi változó átlagának eloszlása:
w42 = np.random.rand(10000, 2)
plt.figure()
(n, bins, patches) = plt.hist(w42.sum(axis=1)/2., bins=30, normed=True)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead. """
## Tíz uniform eloszlású valószínűségi változó átlagának eloszlása:
w410 = np.random.rand(10000, 10)
plt.figure()
(n, bins, patches) = plt.hist(w410.sum(axis=1)/10., bins=30, normed=True)
C:\Users\User\Anaconda3\lib\site-packages\ipykernel_launcher.py:6: MatplotlibDeprecationWarning: The 'normed' kwarg was deprecated in Matplotlib 2.1 and will be removed in 3.1. Use 'density' instead.
import math # Ez a sor vajon mit csinál?
import random
from PIL import Image
import matplotlib.pyplot
import numpy as np
imgx = 512; imgy = 512
image = Image.new("RGB", (imgx, imgy))
pixels = image.load()
f = random.random() * 20 + 10
p = random.random() * math.pi
n = random.randint(10, 20)
print(f, p, n)
for ky in range(imgy):
y = float(ky) / (imgy - 1) * 4 * math.pi - 2 * math.pi
for kx in range(imgx):
x = float(kx) / (imgx - 1) * 4 * math.pi - 2 * math.pi
z = 0.0
for i in range(n):
r = math.hypot(x, y)
a = math.atan2(y, x) + i * math.pi * 2.0 / n
z += math.cos(r * math.sin(a) * f + p)
c = int(round(255 * z / n))
pixels[kx, ky] = (c, c, c)
%matplotlib inline
matplotlib.pyplot.imshow(np.asarray(image),cmap='PuBu');
17.768446797789 0.1737234090058 14
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()