V tomto kurzu se dozvíte o modulu pole Pythonu, rozdílu mezi poli a seznamy a o tom, jak a kdy je použít, pomocí příkladů.
Poznámka: Když lidé říkají pole v Pythonu, nejčastěji hovoří o seznamech Pythonu . V takovém případě navštivte výukový program seznamu Python.
V tomto kurzu se zaměříme na modul s názvem array
. array
Modul nám umožňuje uložit soubor číselných hodnot.
Vytváření polí Pythonu
Chcete-li vytvořit řadu číselných hodnot, musíme array
modul importovat . Například:
import array as arr a = arr.array('d', (1.1, 3.5, 4.5)) print(a)
Výstup
pole ('d', (1,1; 3,5; 4,5))
Zde jsme vytvořili řadu float
typů. Písmeno d
je typový kód. To určuje typ pole během vytváření.
Běžně používané typové kódy jsou uvedeny takto:
Kód | Typ C | Typ Pythonu | Min. Bajtů |
---|---|---|---|
b | podepsaný znak | int | 1 |
B | nepodepsaný znak | int | 1 |
u | Py_UNICODE | Unicode | 2 |
h | podepsal krátce | int | 2 |
H | bez znaménka krátký | int | 2 |
i | podepsané int | int | 2 |
I | nepodepsané int | int | 2 |
l | podepsal dlouho | int | 4 |
L | bez znaménka dlouho | int | 4 |
f | plovák | plovák | 4 |
d | dvojnásobek | plovák | 8 |
V tomto článku nebudeme diskutovat o různých typech C. V celém tomto článku použijeme dva typy kódů: i
pro celá čísla a d
pro plovoucí čísla .
Poznámka : u
Typový kód pro znaky Unicode je zastaralý od verze 3.3. Nepoužívejte co nejvíce.
Přístup k prvkům pole Python
Pro přístup k prvkům pole používáme indexy:
import array as arr a = arr.array('i', (2, 4, 6, 8)) print("First element:", a(0)) print("Second element:", a(1)) print("Last element:", a(-1))
Výstup
První prvek: 2 Druhý prvek: 4 Poslední prvek: 8
Poznámka : Index začíná od 0 (ne 1) podobně jako seznamy.
Řezání polí Pythonu
Můžeme přistupovat k řadě položek v poli pomocí operátoru krájení :
.
import array as arr numbers_list = (2, 5, 62, 5, 42, 52, 48, 5) numbers_array = arr.array('i', numbers_list) print(numbers_array(2:5)) # 3rd to 5th print(numbers_array(:-5)) # beginning to 4th print(numbers_array(5:)) # 6th to end print(numbers_array(:)) # beginning to end
Výstup
pole ('i', (62, 5, 42)) pole ('i', (2, 5, 62)) pole ('i', (52, 48, 5)) pole ('i', (2 , 5, 62, 5, 42, 52, 48, 5))
Změna a přidání prvků
Pole jsou proměnlivá; jejich prvky lze měnit podobným způsobem jako seznamy.
import array as arr numbers = arr.array('i', (1, 2, 3, 5, 7, 10)) # changing first element numbers(0) = 0 print(numbers) # Output: array('i', (0, 2, 3, 5, 7, 10)) # changing 3rd to 5th element numbers(2:5) = arr.array('i', (4, 6, 8)) print(numbers) # Output: array('i', (0, 2, 4, 6, 8, 10))
Výstup
array ('i', (0, 2, 3, 5, 7, 10)) array ('i', (0, 2, 4, 6, 8, 10))
Můžeme přidat jednu položku do pole pomocí append()
metody, nebo přidat několik položek pomocí extend()
metody.
import array as arr numbers = arr.array('i', (1, 2, 3)) numbers.append(4) print(numbers) # Output: array('i', (1, 2, 3, 4)) # extend() appends iterable to the end of the array numbers.extend((5, 6, 7)) print(numbers) # Output: array('i', (1, 2, 3, 4, 5, 6, 7))
Výstup
pole ('i', (1, 2, 3, 4)) pole ('i', (1, 2, 3, 4, 5, 6, 7))
Můžeme také zřetězit dvě pole pomocí +
operátoru.
import array as arr odd = arr.array('i', (1, 3, 5)) even = arr.array('i', (2, 4, 6)) numbers = arr.array('i') # creating empty array of integer numbers = odd + even print(numbers)
Výstup
pole ('i', (1, 3, 5, 2, 4, 6))
Removing Python Array Elements
We can delete one or more items from an array using Python's del statement.
import array as arr number = arr.array('i', (1, 2, 3, 3, 4)) del number(2) # removing third element print(number) # Output: array('i', (1, 2, 3, 4)) del number # deleting entire array print(number) # Error: array is not defined
Output
array('i', (1, 2, 3, 4)) Traceback (most recent call last): File "", line 9, in print(number) # Error: array is not defined NameError: name 'number' is not defined
We can use the remove()
method to remove the given item, and pop()
method to remove an item at the given index.
import array as arr numbers = arr.array('i', (10, 11, 12, 12, 13)) numbers.remove(12) print(numbers) # Output: array('i', (10, 11, 12, 13)) print(numbers.pop(2)) # Output: 12 print(numbers) # Output: array('i', (10, 11, 13))
Output
array('i', (10, 11, 12, 13)) 12 array('i', (10, 11, 13))
Check this page to learn more about Python array and array methods.
Python Lists Vs Arrays
In Python, we can treat lists as arrays. However, we cannot constrain the type of elements stored in a list. For example:
# elements of different types a = (1, 3.5, "Hello")
If you create arrays using the array
module, all elements of the array must be of the same numeric type.
import array as arr # Error a = arr.array('d', (1, 3.5, "Hello"))
Output
Traceback (most recent call last): File "", line 3, in a = arr.array('d', (1, 3.5, "Hello")) TypeError: must be real number, not str
When to use arrays?
Lists are much more flexible than arrays. They can store elements of different data types including strings. And, if you need to do mathematical computation on arrays and matrices, you are much better off using something like NumPy.
So, what are the uses of arrays created from the Python array module?
The array.array
type is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types. If you need to allocate an array that you know will not change, then arrays can be faster and use less memory than lists.
Pokud pole opravdu nepotřebujete (k propojení s kódem C může být zapotřebí modul pole), použití modulu pole se nedoporučuje.