Python: créer et utiliser des tableaux - comment cela fonctionne
Lors de la programmation avec Python, vous tombez rapidement sur des tableaux. Ce guide Python vous montre comment les créer et les utiliser. Parce que la programmation avec Python n'est pas si difficile.
Créer des listes en Python
Les "tableaux" classiques comme en Java n'existent pas en Python. Cependant, vous pouvez créer des listes dites qui fonctionnent de manière similaire. Vous pouvez également moderniser des tableaux par module, ce que nous vous montrerons dans le deuxième paragraphe.
- Vous pouvez créer une liste avec la commande "a = [1, 2, 3]", par exemple. Cette liste contient trois valeurs entières.
- Par exemple, vous pouvez utiliser la commande "print (a [0])" pour sortir une valeur spécifique. Dans ce cas, le nombre 1 serait sorti car l'ordinateur commence à compter à partir de 0. Vous pouvez également modifier les entrées de liste de la même manière: "a [0] = 15".
- Vous pouvez également créer des listes multidimensionnelles. Un exemple de ceci est la commande "b = [[1, 2, 3], [4, 5, 6]]". La commande "print (b [1] [0])" afficherait le chiffre 4.
- Vous pouvez imprimer certaines zones de la liste avec "print (a [2: 5])" ou redéfinir plusieurs entrées de liste en même temps (commande: "a [0: 2] = [0, 1]").
- Les listes en coopération avec les boucles for sont très pratiques. Dans la boucle "for i in a:", i suppose chaque valeur de la liste une fois lors de l'itération (l'une après l'autre). Il est modifié après chaque exécution. Mais attention: lors de l'itération sur une liste bidimensionnelle avec une boucle for, l'itérable est également une liste. Ici, vous avez besoin d'une boucle for dans une boucle for.
- En plus des listes, il existe une autre façon d'utiliser les tableaux en Python. Pour ce faire, vous devez d'abord installer le module approprié:
Tableaux en Python: installez d'abord le module NumPy
Avant de commencer à créer les tableaux, vous devez d'abord installer le module NumPy. Parce que ce n'est généralement pas pré-installé. Voici comment cela fonctionne sous Windows:
- Ouvrez l'invite de commande sur votre PC avec la combinaison de touches [touche Windows] + [R] et la commande "CMD".
- Passez ensuite au sous-dossier "Scripts" de votre dossier système Python avec une commande de changement de répertoire: Pour ce faire, entrez "cd C: \ Users \ yourusername \ AppData \ Local \ Programs \ Python \ Python36 \ Scripts". Cependant, notez que le chemin d'accès à ce sous-dossier peut varier selon la version du système d'exploitation et la version Python. Vérifiez donc au préalable où se trouve le dossier.
- Exécutez ensuite la commande "pip install numpy" pour installer NumPy.
Guide Python: créer des tableaux
Maintenant, vous pouvez facilement créer un tableau avec le module NumPy:
- Vous devez d'abord importer le module NumPy avec la commande "import numpy as np" (sans les guillemets).
- Vous pouvez maintenant créer un premier tableau avec la commande "x = np.array ([1, 2, 3, 4])". Dans ce cas, le tableau est enregistré sous la variable "x".
- Vous pouvez facilement avoir cette sortie de tableau pour tester avec la commande "print (x)".
- Vous pouvez également créer des tableaux avec plusieurs "dimensions". Un exemple de ceci est: "y = np.array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]])". Si vous imprimez ce tableau avec "print (y)", vous verrez qu'un champ 3x3 est imprimé. Dans la première ligne, les numéros 1, 2 et 3 sont dans les seconds 4, 5 et 6 et enfin dans les 7, 8 et 9 derniers.
- Si vous le souhaitez, vous pouvez utiliser la commande np.arange (10) pour créer un tableau contenant tous les entiers de 0 à 9.
- La commande "np.arange (2, 10, dtype = np.float)" crée à son tour un tableau qui contient tous les entiers de 2 à 9 sous forme de nombre à virgule flottante ("float"). Donc, cela contient les nombres 2.0, 3.0, 4.0, etc.
- Par exemple, vous pouvez utiliser la commande "np.arange (2, 3, 0.1)" pour créer un tableau contenant des nombres de 2, 0 à 2, 9. Les valeurs sont créées par étapes de 0, 1, c'est-à-dire 2, 0, 2, 1, 2, 2, etc.
- Une autre commande pratique est "np.linspace (1, 2, 3)". Cette commande génère un tableau contenant trois nombres compris entre un et deux. La particularité ici est que les nombres sont toujours à la même distance. Dans ce cas, les nombres 1.0, 1.5 et 2.0 seraient sortis.
- Enfin, il y a la commande "np.indices ((4, 3))". Cela crée un tableau avec de nombreuses dimensions, chaque dimension étant une variation de la précédente. Dans ce cas, deux dimensions sont créées, avec quatre lignes chacune. Les deux dimensions ont trois nombres par ligne.
Plus de conseils sur Python dans nos guides CHIP
Astuce: Sur notre page de sujet sur le langage de programmation Python, vous trouverez d'autres tutoriels sur la programmation. Là, nous vous montrons, par exemple, comment utiliser range et xrange.