Files
mkdocs/docs/Programmation/Python/in.md
2019-05-12 16:17:58 +02:00

210 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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:]
```
![image-20190317181121361](image-20190317181121361.png)
```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 dune chaîne de caractères:
```python
>>> s = input()
4
>>> s
'4'
>>> type(s)
<class 'str'>
```
##### Lecture et initialisation dun 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
```