Python: създаване и използване на масиви - как работи
Свързани Видеоклипове: (Септември 2024).
Когато програмирате с Python, бързо се натъквате на масиви. Това ръководство на Python ви показва как да ги създавате и използвате. Защото програмирането с Python не е толкова трудно.
Създайте списъци в Python
Класическите „масиви“ като в Java не съществуват в Python. Можете обаче да създадете така наречените списъци, които работят по подобен начин. Можете също да преоборудвате масиви за модул, които ще ви покажем във втория параграф.
- Можете да създадете списък например с командата "a = [1, 2, 3]". Този списък съдържа три цели числа.
- Например, можете да използвате командата "print (a [0])", за да изведете конкретна стойност. В този случай числото 1 ще бъде изведено, защото компютърът започва да брои от 0. Можете също да промените записите в списъка по същия начин: "a [0] = 15".
- Можете също да създавате многоизмерни списъци. Пример за това е командата "b = [[1, 2, 3], [4, 5, 6]]". Командата "print (b [1] [0])" ще изведе числото 4.
- Можете да разпечатате определени области от списъка с „print (a [2: 5])“ или да дефинирате едновременно няколко записа в списъка (команда: „a [0: 2] = [0, 1]“).
- Списъците в сътрудничество с за бримки са много практични. В цикъла "за i в a:", приемам всяка стойност в списъка веднъж, когато се повтори (една след друга). Сменя се след всяко изпълнение. Но бъдете внимателни: когато итерацията над двуизмерен списък с цикъл за, цикълът също е списък. Тук се нуждаете от цикъл в цикъл за.
- В допълнение към списъците има и друг начин за използване на масиви в Python. За да направите това, първо трябва да инсталирате подходящия модул:
Масиви в Python: Първо инсталирайте модула NumPy
Преди да започнете да създавате масиви, първо трябва да инсталирате NumPy модула. Тъй като това обикновено не е предварително инсталирано. Ето как работи в Windows:
- Отворете командния ред на вашия компютър с комбинацията от клавиши [клавиш Windows] + [R] и командата "CMD".
- След това използвайте командата за промяна на директорията, за да промените в подпапката "Скриптове" на вашата системна папка Python: За да направите това, въведете "cd C: \ Users \ yourusername \ AppData \ Local \ Programs \ Python \ Python36 \ Scripts". Имайте предвид обаче, че пътят до тази подпапка може да варира в зависимост от версията на операционната система и версията Python. Затова предварително проверете къде е папката.
- След това изпълнете командата "pip install numpy", за да инсталирате NumPy.
Ръководство на Python: създаване на масиви
Сега можете лесно да създадете масив с NumPy модула:
- Първо трябва да импортирате NumPy модула с командата "import numpy as np" (без кавички).
- Сега можете да създадете първи масив с командата "x = np.array ([1, 2, 3, 4])". В този случай масивът се записва под променливата "x".
- Можете лесно да имате този матричен изход за тестване с командата "print (x)".
- Можете също да създадете масиви с множество "размери". Пример за това е: "y = np.array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]]"). Ако отпечатате този масив с „print (y)“, ще видите, че е отпечатано поле 3x3. В първия ред числата 1, 2 и 3 са във втория 4, 5 и 6 и накрая в последния 7, 8 и 9.
- Ако искате, можете да използвате командата np.arange (10), за да създадете масив, който съдържа всички цели числа от 0 до 9.
- Командата "np.arange (2, 10, dtype = np.float)" от своя страна създава масив, който съдържа всички цели числа от 2 до 9 като число с плаваща запетая ("float"). Така че това съдържа числата 2.0, 3.0, 4.0 и т.н.
- Например, можете да използвате командата "np.arange (2, 3, 0.1)", за да създадете масив, който съдържа числа от 2.0 до 2.9. Стойностите се създават на стъпки от 0, 1, т.е. 2.0, 2.1, 2.2 и т.н.
- Друга практическа команда е "np.linspace (1, 2, 3)". Тази команда извежда масив, който съдържа три числа между едно и две. Особеното тук е, че числата са винаги на едно и също разстояние. В този случай ще бъдат изведени числата 1.0, 1.5 и 2.0.
- Накрая има командата "np.indices ((4, 3))". Това създава масив с много измерения, като всяко измерение е разновидност на предишното. В този случай се създават две измерения, с по четири реда всеки. И двете измерения имат три числа на ред.
Повече съвети за Python в нашите ръководства за CHIP
Съвет: На нашата тема тема на езика за програмиране Python ще намерите допълнителни уроци по програмиране. Там ви показваме например как можете да използвате range и xrange.