„Python“ skaitinių reikšmių masyvas

Šioje pamokoje sužinosite apie „Python“ masyvo modulį, masyvų ir sąrašų skirtumą bei tai, kaip ir kada juos naudoti, naudodamiesi pavyzdžiais.

Pastaba: Kai žmonės sako masyvus „Python“, jie dažniausiai kalba apie „ Python“ sąrašus . Tokiu atveju apsilankykite „Python“ sąrašo pamokoje.

Šioje pamokoje sutelksime dėmesį į pavadintą modulį array. arrayModulis leidžia mums laikyti daug reikšmes kolekciją.

„Python“ masyvų kūrimas

Norėdami sukurti skaitinių verčių masyvą, turime importuoti arraymodulį. Pavyzdžiui:

 import array as arr a = arr.array('d', (1.1, 3.5, 4.5)) print(a)

Rezultatas

 masyvas ('d', (1.1, 3.5, 4.5))

Čia mes sukūrėme floattipo masyvą . Raidė dyra tipo kodas. Tai nustato masyvo tipą kuriant.

Dažniausiai naudojami tipo kodai išvardyti taip:

Kodas C tipas „Python“ tipas Min. Baitai
b pasirašytas char tarpt 1
B nepasirašyta char tarpt 1
u Py_UNICODE „Unicode“ 2
h pasirašė trumpai tarpt 2
H nepasirašytas trumpas tarpt 2
i pasirašytas tarpt tarpt 2
I nepasirašytas tarpt tarpt 2
l pasirašė ilgai tarpt 4
L nepasirašytas ilgas tarpt 4
f plūdė plūdė 4
d dvigubai plūdė 8

Šiame straipsnyje nenagrinėsime skirtingų C tipų. Šiame visame straipsnyje naudosime du tipo kodus: isveikiesiems ir dplūdiniams.

Pastaba : „ uUnicode“ simbolių tipo kodas yra nebenaudojamas nuo 3.3 versijos. Venkite naudoti kuo daugiau.

Prieiga prie „Python“ masyvo elementų

Mes naudojame indeksus, kad pasiektume masyvo elementus:

 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))

Rezultatas

 Pirmasis elementas: 2 Antrasis elementas: 4 Paskutinis elementas: 8

Pastaba : indeksas prasideda nuo 0 (ne 1), panašaus į sąrašus.

„Python“ masyvų pjaustymas

Mes galime pasiekti masyvo elementų asortimentą naudodami pjaustymo operatorių :.

 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

Rezultatas

 masyvas ('i', (62, 5, 42)) masyvas ('i', (2, 5, 62)) masyvas ('i', (52, 48, 5)) masyvas ('i', (2 (5, 62, 5, 42, 52, 48, 5)

Elementų keitimas ir pridėjimas

Masyvai yra keičiami; jų elementai gali būti keičiami panašiai kaip sąrašai.

 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))

Rezultatas

 masyvas ('i', (0, 2, 3, 5, 7, 10)) masyvas ('i', (0, 2, 4, 6, 8, 10))

Mes galime pridėti vieną elementą prie masyvo naudodami append()metodą arba pridėti kelis elementus naudodami extend()metodą.

 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))

Rezultatas

 masyvas ('i', (1, 2, 3, 4)) masyvas ('i', (1, 2, 3, 4, 5, 6, 7))

Taip pat galime susieti dvi masyvas naudodami +operatorių.

 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)

Rezultatas

 masyvas ('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.

Masyvo modulio naudoti nerekomenduojama, nebent jums tikrai nereikia masyvų (masyvo modulio gali prireikti sąsajai su C kodu).

Įdomios straipsniai...