Update
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
|
||||
|
||||
# class
|
||||
# Les classes
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -33,6 +33,18 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**.
|
||||
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964}
|
||||
```
|
||||
|
||||
```python
|
||||
# Liste l de couples transformée en dictionnaire
|
||||
>>> l = [('a',1), ('b',2)]
|
||||
>>> dict(l)
|
||||
{'a': 1, 'b': 2}
|
||||
```
|
||||
|
||||
```python
|
||||
>>> dict(zip('abc',range(3)))
|
||||
{'a': 0, 'b': 1, 'c': 2}
|
||||
```
|
||||
|
||||
##### Accéder à un item:
|
||||
|
||||
```python
|
||||
@@ -82,6 +94,15 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**.
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
```
|
||||
|
||||
##### Ajouter des valeurs (update):
|
||||
|
||||
```python
|
||||
>>> d = {'a':0}
|
||||
>>> d.update(zip('bcd',range(1,4)))
|
||||
>>> d
|
||||
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
|
||||
```
|
||||
|
||||
##### Vérifier la présence d'une clé (in):
|
||||
|
||||
```python
|
||||
@@ -181,7 +202,7 @@ language python
|
||||
version 3.7
|
||||
```
|
||||
|
||||
Vérifier si une clé existe dans un dictionnaire:
|
||||
##### Vérifier si une clé existe dans un dictionnaire:
|
||||
|
||||
```python
|
||||
>>> dict = {'language': 'python', 'version': '3.7'}
|
||||
@@ -191,7 +212,7 @@ Vérifier si une clé existe dans un dictionnaire:
|
||||
'language' est dans dict
|
||||
```
|
||||
|
||||
Longueur d'un dictionnaire:
|
||||
##### Longueur d'un dictionnaire:
|
||||
|
||||
```python
|
||||
>>> dict = {'language': 'python', 'version': '3.7'}
|
||||
@@ -199,33 +220,96 @@ Longueur d'un dictionnaire:
|
||||
2
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Copier un dictionnaire (copy):
|
||||
|
||||
```python
|
||||
>>> autre_dict = dict.copy()
|
||||
>>> autre_dict
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
|
||||
>>> autre_dict['language'] = 'PYTHON'
|
||||
>>> autre_dict
|
||||
{'language': 'PYTHON', 'version': '3.7'}
|
||||
>>> dict
|
||||
{'language': 'python', 'version': '3.7'}
|
||||
```
|
||||
|
||||
##### Fromkeys():
|
||||
|
||||
```python
|
||||
>>> d3 = {}
|
||||
>>> d3 = {}.fromkeys('abcde', 0)
|
||||
>>> d3
|
||||
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
| Méthode | Description |
|
||||
| ------------ | ----------- |
|
||||
| clear() | |
|
||||
| copy() | |
|
||||
| fromkeys() | |
|
||||
| get() | |
|
||||
| items() | |
|
||||
| keys() | |
|
||||
| pop() | |
|
||||
| popitem() | |
|
||||
| setdefault() | |
|
||||
| update() | |
|
||||
| values() | |
|
||||
| Méthode | Description |
|
||||
| -------------------- | ------------------------------------------------------------ |
|
||||
| d.clear() | supprime tous les éléments de `d` |
|
||||
| d.copy() | shallow copie de `d` |
|
||||
| {}.fromkeys(s,v) | créée un dict avec les clés de `s` et la valeur `v` |
|
||||
| d.get(k [,v]) | envoie la valeur `d[k]` si elle existe v sinon |
|
||||
| d.items() | liste des items `(k,v)` de `d` |
|
||||
| d.keys() | liste des clés |
|
||||
| d.pop(k [,v]) | enlève `d[k]` s’il existe et renvoie sa valeur ou `v` sinon |
|
||||
| d.popitem() | supprime un item `(k,v)` et retourne l’item sous forme de tuple |
|
||||
| d.setdefault(k [,v]) | `d[k]` si elle existe sinon `v` et rajoute `d[k] = v` |
|
||||
| d.update(s) | `s` est une liste de tuples que l’on rajoute à `d` |
|
||||
| d.values() | liste des valeurs de `d` |
|
||||
|
||||
|
||||
|
||||
#### Dictionnaires persistants:
|
||||
|
||||
Python permet de créer des dictionnaires persistants, grâce au module `shelve`.
|
||||
|
||||
`shelve` fournit une solution de persistance de type “base de données” très simple qui sera gérée automatiquement dans un fichier.
|
||||
|
||||
La méthode `shelve.open('f')` crée dans le répertoire courant de votre ordinateur, un fichier de sauvegarde “f.db” s’il n’existe pas, et retourne un objet de type `shelve` ; un `shelve` fonctionne comme un dictionnaire. La plupart des opérations et méthodes des dictionnaires lui sont applicables ; toute modification appliquée au `shelve` est automatiquement sauvegardée. La méthode `shelve.close` permet de fermer le `shelve`, comme pour un fichier.
|
||||
|
||||
```python
|
||||
>>> import shelve
|
||||
>>> t = [0,1,2,3,4,5,6,7]
|
||||
>>> p = (1,2,3)
|
||||
>>> i = 23
|
||||
>>> s = 'Bonjour'
|
||||
>>> db = shelve.open('data')
|
||||
>>> db['liste'] = t
|
||||
>>> db['point'] = p
|
||||
>>> db['entier'] = i
|
||||
>>> db['chaine'] = s
|
||||
>>> print(dict(db))
|
||||
{'point': (1, 2, 3), 'entier': 23, 'liste': [0, 1, 2, 3, 4, 5, 6, 7], 'chaine': 'Bonjour'}
|
||||
>>> db.close()
|
||||
>>> exit()
|
||||
|
||||
~$ ls -la
|
||||
-rw-r--r-- 1 bruno staff 16384 25 mar 08:55 data
|
||||
|
||||
# On relance une session Python
|
||||
|
||||
>>> import shelve
|
||||
>>> with shelve.open('data') as db:
|
||||
... print(db['liste'])
|
||||
... for k in db:
|
||||
... print(db[k])
|
||||
...
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
(1, 2, 3)
|
||||
23
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
Bonjour
|
||||
```
|
||||
|
||||
Si votre code modifie plusieurs fois certaines entrées lors de la même session, lors de l’ouverture du `shelve`, il est important, dans la méthode `open` associée au `shelve`, de mettre le paramètre `writeback` à vrai, comme suit :
|
||||
|
||||
```python
|
||||
shelve.open('data', writeback=True)
|
||||
```
|
||||
|
||||
Grâce à cette option, chaque fois qu’une modification est réalisée au `shelve`, cette modification est correctement répercutée sur la mémoire morte (le disque dur) de votre ordinateur.
|
||||
|
||||
|
||||
@@ -38,7 +38,23 @@ Parcourrir un fichier ligne par ligne:
|
||||
>>> for x in fichier:
|
||||
... print(x)
|
||||
...
|
||||
```
|
||||
|
||||
```python
|
||||
>>> with open("pecl-help.txt") as fichier:
|
||||
... for line in fichier:
|
||||
... print(line, end='')
|
||||
...
|
||||
```
|
||||
|
||||
Ouverture d'un fichier binaire:
|
||||
|
||||
```python
|
||||
>>> with open('file', 'rb') as fichierbinaire:
|
||||
... octets = fichierbinaire.read() # le fichier est lu en entier
|
||||
... print("on a lu un objet de type", type(octets))
|
||||
... for i, octet in enumerate(octets):
|
||||
... print(f"{i} → {repr(chr(octet))} [{hex(octet)}]")
|
||||
```
|
||||
|
||||
|
||||
@@ -56,8 +72,8 @@ fichier.close()
|
||||
##### Type d'ouverture:
|
||||
|
||||
```python
|
||||
r, pour une ouverture en lecture (READ).
|
||||
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas python le crée.
|
||||
r, pour une ouverture en lecture (READ). (Par défaut)
|
||||
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas, Python le crée.
|
||||
a, pour une ouverture en mode ajout à la fin du fichier (APPEND). Si le fichier n'existe pas python le crée.
|
||||
b, pour une ouverture en mode binaire.
|
||||
t, pour une ouverture en mode texte.
|
||||
@@ -92,7 +108,7 @@ if os.path.exists("empty_folder"):
|
||||
|
||||
|
||||
|
||||
#### Chemins
|
||||
#### Chemins (os.path)
|
||||
|
||||
##### Méthodes:
|
||||
|
||||
@@ -206,3 +222,37 @@ os.rename(old, new) → Renomme le fichier / dossier indiqué
|
||||
|
||||
|
||||
|
||||
#### pathlib
|
||||
|
||||
Depuis Python 3.4, le module `os.path` est obsolète et est remplacé par la librairie `pathlib`.
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
|
||||
help(pathlib)
|
||||
```
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
filename = 'scratch.py'
|
||||
path = Path(filename)
|
||||
|
||||
if path.exists():
|
||||
print("existe")
|
||||
print(path.stat().st_size) # taille
|
||||
print(path.stat().st_mtime) # dernière modif
|
||||
|
||||
try:
|
||||
path.unlink()
|
||||
except FileNotFoundError:
|
||||
print("Pas de fichier à supprimer")
|
||||
```
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
dirpath = Path('.') # répertoire courant
|
||||
|
||||
for py in dirpath.glob("*.py"):
|
||||
print(py) # liste des fichiers Python du répertoire courant
|
||||
```
|
||||
|
||||
|
||||
65
docs/Programmation/Python/for.md
Normal file
65
docs/Programmation/Python/for.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# For
|
||||
|
||||
|
||||
|
||||
##### Range:
|
||||
|
||||
```python
|
||||
>>> somme = 0
|
||||
>>> for i in range(10):
|
||||
... somme += i
|
||||
...
|
||||
>>> print(somme)
|
||||
45
|
||||
```
|
||||
|
||||
##### Parcourir une liste:
|
||||
|
||||
```python
|
||||
>>> thislist = ["alpha", "beta", "gamma"]
|
||||
>>> for elem in thislist:
|
||||
... print(elem)
|
||||
...
|
||||
alpha
|
||||
beta
|
||||
gamma
|
||||
```
|
||||
|
||||
##### Parcourir une chaine:
|
||||
|
||||
```python
|
||||
>>> language = "Python"
|
||||
>>> for c in language:
|
||||
... print("Caractère : ", c)
|
||||
...
|
||||
Caractère : P
|
||||
Caractère : y
|
||||
Caractère : t
|
||||
Caractère : h
|
||||
Caractère : o
|
||||
Caractère : n
|
||||
```
|
||||
|
||||
##### Parcourir une chaine par les indices:
|
||||
|
||||
```python
|
||||
>>> language = "Python"
|
||||
>>> for i in range(len(language)):
|
||||
... print("Caractère d'indice",i," :",language[i])
|
||||
...
|
||||
Caractère d'indice 0 : P
|
||||
Caractère d'indice 1 : y
|
||||
Caractère d'indice 2 : t
|
||||
Caractère d'indice 3 : h
|
||||
Caractère d'indice 4 : o
|
||||
Caractère d'indice 5 : n
|
||||
```
|
||||
|
||||
##### Plusieurs variables dans une boucle for:
|
||||
|
||||
```python
|
||||
entrees = [(1, 2), (3, 4), (5, 6)]
|
||||
for a, b in entrees:
|
||||
print(f"a={a} b={b}")
|
||||
```
|
||||
|
||||
BIN
docs/Programmation/Python/image-20190317181121361.png
Normal file
BIN
docs/Programmation/Python/image-20190317181121361.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
209
docs/Programmation/Python/in.md
Normal file
209
docs/Programmation/Python/in.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# In
|
||||
|
||||
|
||||
|
||||
##### Test si un item est présent dans une liste:
|
||||
|
||||
```python
|
||||
>>> language = ["Python", "Perl", "C++"]
|
||||
>>> i = "Python"
|
||||
>>> if i in language:
|
||||
... print("Python appartient à language")
|
||||
...
|
||||
Python appartient à language
|
||||
```
|
||||
|
||||
##### Test si une liste est présent dans une autre liste:
|
||||
|
||||
```python
|
||||
>>> liste1 = [9,18,3,5,7,21]
|
||||
>>> liste2 = [9,18,[3,5,7],21]
|
||||
>>> [3,5,7] in liste1
|
||||
False
|
||||
>>> [3,5,7] in liste2
|
||||
True
|
||||
```
|
||||
|
||||
##### Test su une séquence est présent dans une chaine:
|
||||
|
||||
```python
|
||||
>>> language = "Python"
|
||||
>>> 'thon' in language
|
||||
True
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Slicing:
|
||||
|
||||
##### Sous-séquence:
|
||||
|
||||
```python
|
||||
>>> str = "Bonjour, ça va ?"
|
||||
>>> str[1:3]
|
||||
'on'
|
||||
>>> str[:3]
|
||||
'Bon'
|
||||
>>> str[3:]
|
||||
'jour, ça va ?'
|
||||
```
|
||||
|
||||
##### Copie de séquence:
|
||||
|
||||
```python
|
||||
>>> prem = [1,2,3,5,7]
|
||||
>>> sec = prem[:]
|
||||
>>> sec
|
||||
[1, 2, 3, 5, 7]
|
||||
```
|
||||
|
||||
##### Pas:
|
||||
|
||||
```python
|
||||
>>> language = "Python"
|
||||
>>> language[::2]
|
||||
'Pto'
|
||||
# On prend 1 lettre sur 2
|
||||
|
||||
>>> language[::-1]
|
||||
'nohtyP'
|
||||
# On part de la fin
|
||||
```
|
||||
|
||||
##### Gestion mémoire des séquences:
|
||||
|
||||
```python
|
||||
>>> prem = [2, 3]
|
||||
>>> prem = sec = [2, 3]
|
||||
>>> id(prem)
|
||||
4468993928
|
||||
>>> id(sec)
|
||||
4468993928
|
||||
|
||||
>>> trois = [2, 3]
|
||||
>>> id(trois)
|
||||
4468967496
|
||||
|
||||
>>> prem is sec
|
||||
True
|
||||
>>> prem is trois
|
||||
False
|
||||
>>> prem == trois
|
||||
True
|
||||
|
||||
>>> prem.append(5)
|
||||
>>> prem
|
||||
[2, 3, 5]
|
||||
>>> sec
|
||||
[2, 3, 5]
|
||||
>>> trois
|
||||
[2, 3]
|
||||
```
|
||||
|
||||
|
||||
|
||||
```python
|
||||
1 prem = sec = [1, 3]
|
||||
2 trois = [1, 3]
|
||||
3 prem[0] = 2
|
||||
4 prem.append(5)
|
||||
5 prem.extend([7, 11])
|
||||
6 t = 'Bonjour'
|
||||
7 t2 = 'B' + t[1:]
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
>>> tex = "bonjour"
|
||||
>>> prem = [2, 3, 5, 7, 8, 9, 10, 17]
|
||||
|
||||
>>> prem[4:7] = [11, 13] # on remplace les éléments 4 à 7 exclu
|
||||
>>> prem
|
||||
[2, 3, 5, 7, 11, 13, 17]
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Pack / Unpack:
|
||||
|
||||
|
||||
|
||||
```python
|
||||
>>> tp = 2, 3, 5 # on crée un tuple
|
||||
>>> type(tp)
|
||||
<class 'tuple'>
|
||||
>>> x, y, z = tp # les 3 variables x, y, z prennent les valeurs des 3 éléments du tuple
|
||||
>>> x
|
||||
2
|
||||
>>> y
|
||||
3
|
||||
>>> z
|
||||
5
|
||||
```
|
||||
|
||||
```python
|
||||
>>> x, y = 33, 666
|
||||
>>> x, y = y, x # permutation
|
||||
>>> x
|
||||
666
|
||||
>>> y
|
||||
33
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### Lecture et initialisation d’une chaîne de caractères:
|
||||
|
||||
```python
|
||||
>>> s = input()
|
||||
4
|
||||
>>> s
|
||||
'4'
|
||||
>>> type(s)
|
||||
<class 'str'>
|
||||
```
|
||||
|
||||
##### Lecture et initialisation d’un tuple de valeurs:
|
||||
|
||||
```python
|
||||
>>> eval("2 + 2")
|
||||
4
|
||||
|
||||
>>> t = eval(input())
|
||||
2, 3, 4, 5
|
||||
>>> t
|
||||
(2, 3, 4, 5)
|
||||
>>> type(t)
|
||||
<class 'tuple'>
|
||||
|
||||
>>> t = eval(input())
|
||||
"alpha", "beta", "gamma"
|
||||
>>> t
|
||||
('alpha', 'beta', 'gamma')
|
||||
>>> type(t)
|
||||
<class 'tuple'>
|
||||
|
||||
```
|
||||
|
||||
##### Création d'une séquence à partir d'une autre:
|
||||
|
||||
```python
|
||||
>>> t = (1, 2, 3, 4)
|
||||
>>> t
|
||||
(1, 2, 3, 4) # tuple
|
||||
>>> l = list(t)
|
||||
>>> l
|
||||
[1, 2, 3, 4] # liste
|
||||
|
||||
>>> l = list("Bonjour") # str
|
||||
>>> l
|
||||
['B', 'o', 'n', 'j', 'o', 'u', 'r'] # liste
|
||||
|
||||
|
||||
```
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
|
||||
|
||||
1. collections:
|
||||
1. [liste](liste.md)
|
||||
2. [dictionnaire](dictionnaire.md)
|
||||
3. [tuple](tuple.md)
|
||||
4. [set](set.md)
|
||||
1. [liste []](liste.md)
|
||||
2. [dictionnaire {}](dictionnaire.md)
|
||||
3. [tuple ()](tuple.md)
|
||||
4. [set {}](set.md)
|
||||
2. [class - objet](class.md)
|
||||
3. [date](date.md)
|
||||
4. [fichiers](fichiers.md)
|
||||
@@ -25,6 +25,16 @@ https://www.w3schools.com/python/default.asp
|
||||
|
||||
|
||||
|
||||
| Hashable (non modifiable) | Unhashable |
|
||||
| ------------------------- | --------------- |
|
||||
| int | liste [] |
|
||||
| float | set {} |
|
||||
| bool | dictionnaire {} |
|
||||
| str | |
|
||||
| tuples () | |
|
||||
|
||||
|
||||
|
||||
#### Instruction de boucles
|
||||
|
||||
##### while:
|
||||
26
docs/Programmation/Python/json.md
Normal file
26
docs/Programmation/Python/json.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# json
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
import json
|
||||
|
||||
# En partant d'une donnée construite à partir de types de base
|
||||
data = [
|
||||
# des types qui ne posent pas de problème
|
||||
[1, 2, 'a', [3.23, 4.32], {'eric': 32, 'jean': 43}],
|
||||
# un tuple
|
||||
(1, 2, 3),
|
||||
]
|
||||
|
||||
# sauver ceci dans un fichier
|
||||
with open("s1.json","w", encoding='utf-8') as json_output:
|
||||
json.dump(data, json_output)
|
||||
|
||||
# et relire le résultat
|
||||
with open("s1.json", encoding='utf-8') as json_input:
|
||||
data2 = json.load(json_input)
|
||||
```
|
||||
|
||||
@@ -251,6 +251,11 @@ False
|
||||
>>> a.extend(b)
|
||||
>>> print(a)
|
||||
[1, 2, 3, 4, 5, 6]
|
||||
|
||||
>>> a.extend([7, 8, 9])
|
||||
>>> print(a)
|
||||
[1, 2, 3, 7, 8, 9]
|
||||
|
||||
>>> c = a + b
|
||||
>>> print(c)
|
||||
[1, 2, 3, 4, 5, 6, 4, 5, 6]
|
||||
@@ -272,6 +277,21 @@ if "alpha" in thislist:
|
||||
print("Oui, 'alpha' est dans la liste")
|
||||
```
|
||||
|
||||
##### Liste d'éléments de types différents:
|
||||
|
||||
```python
|
||||
>>> s = [1, 3, 3.14, ("bon","jour"), [5, 7]]
|
||||
>>> len(s)
|
||||
5
|
||||
>>> len(s[3]) # tuple
|
||||
2
|
||||
>>> len(s[3][1]) # tuple - str "jour"
|
||||
4
|
||||
>>> s[4][1] = 666 # sous-liste - int 7
|
||||
>>> s
|
||||
[1, 3, 3.14, ('bon', 'jour'), [5, 666]]
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
170
docs/Programmation/Python/requests.md
Normal file
170
docs/Programmation/Python/requests.md
Normal file
@@ -0,0 +1,170 @@
|
||||
# Requests
|
||||
|
||||
|
||||
|
||||
https://realpython.com/python-requests/
|
||||
|
||||
https://realpython.com/caching-external-api-requests/
|
||||
|
||||
|
||||
|
||||
```bash
|
||||
pip3 install requests
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Requête GET:
|
||||
|
||||
```python
|
||||
>>> import requests
|
||||
>>> requests.get('https://api.github.com')
|
||||
<Response [200]>
|
||||
|
||||
>>> requests.get('https://api.github.com', timeout=1)
|
||||
<Response [200]>
|
||||
# nb de second avant un timeout
|
||||
```
|
||||
|
||||
##### Status Code:
|
||||
|
||||
```python
|
||||
>>> response = requests.get('https://api.github.com')
|
||||
>>> print(response)
|
||||
<Response [200]>
|
||||
>>> response.status_code
|
||||
200
|
||||
>>> if response.status_code == 200:
|
||||
... print('Success!')
|
||||
... elif response.status_code == 404:
|
||||
... print('Not Found.')
|
||||
...
|
||||
Success!
|
||||
```
|
||||
|
||||
```python
|
||||
import requests
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
for url in ['https://api.github.com', 'https://api.github.com/invalid']:
|
||||
try:
|
||||
response = requests.get(url)
|
||||
|
||||
# If the response was successful, no Exception will be raised
|
||||
response.raise_for_status()
|
||||
except HTTPError as http_err:
|
||||
print(f'HTTP error occurred: {http_err}') # Python 3.6
|
||||
except Exception as err:
|
||||
print(f'Other error occurred: {err}') # Python 3.6
|
||||
else:
|
||||
print('Success!')
|
||||
|
||||
# la 1ere url répond par un Success
|
||||
# la 2nde par une erreur
|
||||
```
|
||||
|
||||
##### Content:
|
||||
|
||||
```python
|
||||
# bytes
|
||||
>>> response.content
|
||||
b'{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}'
|
||||
|
||||
# string
|
||||
>>> response.encoding = 'utf-8'
|
||||
>>> response.text
|
||||
|
||||
# JSON
|
||||
>>> response.json()
|
||||
{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': 'https://github.com/settings/connections/applications{/client_id}', 'authorizations_url': 'https://api.github.com/authorizations', 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}', 'commit_search_url': 'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}', 'emails_url': 'https://api.github.com/user/emails', 'emojis_url': 'https://api.github.com/emojis', 'events_url': 'https://api.github.com/events', 'feeds_url': 'https://api.github.com/feeds', 'followers_url': 'https://api.github.com/user/followers', 'following_url': 'https://api.github.com/user/following{/target}', 'gists_url': 'https://api.github.com/gists{/gist_id}', 'hub_url': 'https://api.github.com/hub', 'issue_search_url': 'https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}', 'issues_url': 'https://api.github.com/issues', 'keys_url': 'https://api.github.com/user/keys', 'notifications_url': 'https://api.github.com/notifications', 'organization_repositories_url': 'https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}', 'organization_url': 'https://api.github.com/orgs/{org}', 'public_gists_url': 'https://api.github.com/gists/public', 'rate_limit_url': 'https://api.github.com/rate_limit', 'repository_url': 'https://api.github.com/repos/{owner}/{repo}', 'repository_search_url': 'https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}', 'current_user_repositories_url': 'https://api.github.com/user/repos{?type,page,per_page,sort}', 'starred_url': 'https://api.github.com/user/starred{/owner}{/repo}', 'starred_gists_url': 'https://api.github.com/gists/starred', 'team_url': 'https://api.github.com/teams', 'user_url': 'https://api.github.com/users/{user}', 'user_organizations_url': 'https://api.github.com/user/orgs', 'user_repositories_url': 'https://api.github.com/users/{user}/repos{?type,page,per_page,sort}', 'user_search_url': 'https://api.github.com/search/users?q={query}{&page,per_page,sort,order}'}
|
||||
# retourne un dictionnaire
|
||||
```
|
||||
|
||||
##### Headers:
|
||||
|
||||
```python
|
||||
>>> response.headers
|
||||
{'Server': 'GitHub.com', 'Date': 'Fri, 29 Mar 2019 15:32:44 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Status': '200 OK', 'X-RateLimit-Limit': '60', 'X-RateLimit-Remaining': '59', 'X-RateLimit-Reset': '1553877164', 'Cache-Control': 'public, max-age=60, s-maxage=60', 'Vary': 'Accept', 'ETag': 'W/"7dc470913f1fe9bb6c7355b50a0737bc"', 'X-GitHub-Media-Type': 'github.v3; format=json', 'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'deny', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'Content-Security-Policy': "default-src 'none'", 'Content-Encoding': 'gzip', 'X-GitHub-Request-Id': 'B245:1134:87E5:14D2A:5C9E3A9C'}
|
||||
|
||||
# retourne un dictionnaire
|
||||
|
||||
>>> response.headers['Content-Type']
|
||||
'application/json; charset=utf-8'
|
||||
```
|
||||
|
||||
##### Query strings parameters:
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
# Search GitHub's repositories for requests
|
||||
response = requests.get(
|
||||
'https://api.github.com/search/repositories',
|
||||
params={'q': 'requests+language:python'},
|
||||
)
|
||||
|
||||
# Inspect some attributes of the `requests` repository
|
||||
json_response = response.json()
|
||||
repository = json_response['items'][0]
|
||||
print(f'Repository name: {repository["name"]}') # Python 3.6+
|
||||
print(f'Repository description: {repository["description"]}') # Python 3.6+
|
||||
|
||||
Repository name: requests
|
||||
Repository description: Python HTTP Requests for Humans™ ✨🍰✨
|
||||
```
|
||||
|
||||
##### Autres méthodes HTTP:
|
||||
|
||||
```python
|
||||
>>> requests.post('https://httpbin.org/post', data={'key':'value'})
|
||||
>>> requests.put('https://httpbin.org/put', data={'key':'value'})
|
||||
>>> requests.delete('https://httpbin.org/delete')
|
||||
>>> requests.head('https://httpbin.org/get')
|
||||
>>> requests.patch('https://httpbin.org/patch', data={'key':'value'})
|
||||
>>> requests.options('https://httpbin.org/get')
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### Requête POST:
|
||||
|
||||
```python
|
||||
>>> requests.post('https://httpbin.org/post', data={'key':'value'})
|
||||
<Response [200]>
|
||||
```
|
||||
|
||||
```python
|
||||
>>> response = requests.post('https://httpbin.org/post', json={'key':'value'})
|
||||
>>> json_response = response.json()
|
||||
>>> json_response['data']
|
||||
'{"key": "value"}'
|
||||
>>> json_response['headers']['Content-Type']
|
||||
'application/json'
|
||||
```
|
||||
|
||||
```python
|
||||
>>> response = requests.post('https://httpbin.org/post', json={'key':'value'})
|
||||
>>> response.request.headers['Content-Type']
|
||||
'application/json'
|
||||
>>> response.request.url
|
||||
'https://httpbin.org/post'
|
||||
>>> response.request.body
|
||||
b'{"key": "value"}'
|
||||
```
|
||||
|
||||
|
||||
|
||||
Authentification:
|
||||
|
||||
```python
|
||||
>>> from requests.auth import HTTPBasicAuth
|
||||
>>> from getpass import getpass
|
||||
>>> requests.get(
|
||||
... 'https://api.github.com/user',
|
||||
... auth=HTTPBasicAuth('bruno@xxxxx.info', getpass())
|
||||
... )
|
||||
Password:
|
||||
<Response [200]>
|
||||
```
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Set
|
||||
# Set (ensemble)
|
||||
|
||||
|
||||
|
||||
Une liste est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter.
|
||||
Un set est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter.
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,17 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set
|
||||
{'alpha', 'beta', 'gamma'}
|
||||
>>> type(un_set)
|
||||
<class 'set'>
|
||||
```
|
||||
|
||||
```python
|
||||
>>> autre_set = {"alpha", "beta", "gamma", "beta", "alpha"}
|
||||
>>> len(autre_set)
|
||||
3
|
||||
>>> autre_set
|
||||
{'beta', 'alpha', 'gamma'}
|
||||
|
||||
```
|
||||
|
||||
```python
|
||||
@@ -54,6 +65,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
|
||||
>>> un_set.remove("beta")
|
||||
>>> un_set
|
||||
{'gamma', 'alpha'}
|
||||
|
||||
# Si on retire un élément qui n'existe pas => Erreur
|
||||
>>> un_set.remove("delta")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
KeyError: 'delta'
|
||||
```
|
||||
|
||||
##### Supprimer un item (discard):
|
||||
@@ -63,6 +80,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
|
||||
>>> un_set.discard("beta")
|
||||
>>> un_set
|
||||
{'gamma', 'alpha'}
|
||||
|
||||
# Si on retire un élément qui n'existe pas.
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set.discard("delta")
|
||||
>>> un_set
|
||||
{'alpha', 'gamma', 'beta'}
|
||||
```
|
||||
|
||||
##### Vider un set:
|
||||
@@ -105,6 +128,23 @@ print("alpha" in un_set)
|
||||
True
|
||||
```
|
||||
|
||||
##### Set => pas d'indice:
|
||||
|
||||
```python
|
||||
>>> un_set = {"alpha", "beta", "gamma"}
|
||||
>>> un_set[0]
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'set' object does not support indexing
|
||||
```
|
||||
|
||||
##### Opérateurs:
|
||||
|
||||
- `a | b` (union),
|
||||
- `a & b` (intersection),
|
||||
- `a - b` (différence),
|
||||
- `a ^ b` (différence symétrique)
|
||||
|
||||
|
||||
|
||||
#### Méthodes:
|
||||
|
||||
@@ -2,6 +2,51 @@
|
||||
|
||||
|
||||
|
||||
```python
|
||||
>>> mon_str = "bonjour"
|
||||
>>> print(mon_str)
|
||||
bonjour
|
||||
|
||||
>>> long_str = """***********
|
||||
... * Bonjour *
|
||||
... ***********
|
||||
... """
|
||||
>>> long_str
|
||||
'***********\n* Bonjour *\n***********\n'
|
||||
>>> print(long_str)
|
||||
***********
|
||||
* Bonjour *
|
||||
***********
|
||||
```
|
||||
|
||||
```python
|
||||
# Concaténation
|
||||
>>> mon_str + " Bruno"
|
||||
'bonjour Bruno'
|
||||
|
||||
# Répétition
|
||||
>>> "ha " * 5
|
||||
'ha ha ha ha ha '
|
||||
|
||||
# Longueur de la chaine
|
||||
>>> len(mon_str)
|
||||
7
|
||||
|
||||
# Indice
|
||||
>>> mon_str[0]
|
||||
'b'
|
||||
>>> mon_str[6]
|
||||
'r'
|
||||
>>> mon_str[len(mon_str)-1]
|
||||
'r'
|
||||
>>> mon_str[-1]
|
||||
'r'
|
||||
>>> mon_str[-3]
|
||||
'o'
|
||||
```
|
||||
|
||||
|
||||
|
||||
##### str.count()
|
||||
|
||||
```python
|
||||
|
||||
39
docs/Programmation/Python/zip.md
Normal file
39
docs/Programmation/Python/zip.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# zip
|
||||
|
||||
|
||||
|
||||
La fonction `zip` associe 2 listes et retourne une liste de tuples.
|
||||
|
||||
```python
|
||||
villes = ["Paris", "Rome", "Göteborg"]
|
||||
pays = ["France", "Italie", "Suède"]
|
||||
|
||||
print(list(zip(villes, pays)))
|
||||
|
||||
for ville, etat in zip(villes, pays):
|
||||
print(ville, " est la capitale de ", etat)
|
||||
|
||||
|
||||
[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')]
|
||||
Paris est la capitale de France
|
||||
Rome est la capitale de Italie
|
||||
Göteborg est la capitale de Suède
|
||||
```
|
||||
|
||||
Si le nombre d'item diffère:
|
||||
|
||||
```python
|
||||
villes = ["Paris", "Rome", "Göteborg"]
|
||||
pays = ["France", "Italie", "Suède", "Suisse"]
|
||||
|
||||
print(list(zip(villes, pays)))
|
||||
|
||||
for ville, etat in zip(villes, pays):
|
||||
print(ville, " est la capitale de ", etat)
|
||||
|
||||
[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')]
|
||||
Paris est la capitale de France
|
||||
Rome est la capitale de Italie
|
||||
Göteborg est la capitale de Suède
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user