Outils pour utilisateurs

Outils du site


tech:python-draft

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
tech:python-draft [2025/04/15 15:32] Jean-Baptistetech:python-draft [2025/05/26 18:56] (Version actuelle) Jean-Baptiste
Ligne 1: Ligne 1:
 +<!DOCTYPE markdown>
 {{tag>Code Python}} {{tag>Code Python}}
  
-Draft Python3+Draft Python3
  
 +## List comprehensions and generator expressions
  
-=== Autres+ (short form: “listcomps” and “genexps”)
  
-<code python>+~~~python 
 +line_list = ['  line 1\n', 'line 2  \n', ' \n', ''
 + 
 +# Generator expression -- returns iterator 
 +stripped_iter = (line.strip() for line in line_list) 
 + 
 +# List comprehension -- returns list 
 +stripped_list = [line.strip() for line in line_list] 
 + 
 +stripped_list = [line.strip() for line in line_list if line != ""
 +~~~ 
 + 
 + 
 +### Autres 
 + 
 +~~~python
 def inc(f, id): def inc(f, id):
     """ Exemple : inc(lambda x : x+1, 0) """     """ Exemple : inc(lambda x : x+1, 0) """
Ligne 15: Ligne 32:
         counter = 0         counter = 0
     return counter     return counter
-</code>+~~~
  
 ------------ ------------
Ligne 23: Ligne 40:
 ------------ ------------
  
-== List unique remove duplicate+## List unique remove duplicate
  
 Source :  Source : 
 http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so
  
-<code python>+~~~python
 def unique(items): def unique(items):
     found = set([])     found = set([])
Ligne 37: Ligne 54:
             keep.append(item)             keep.append(item)
     return keep     return keep
-</code>+~~~
  
 ------------ ------------
  
-== How do you split a list into evenly sized chunks in Python?+## How do you split a list into evenly sized chunks in Python?
  
 Source : http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python Source : http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
  
-<code python>+~~~python
 def chunks(l, n): def chunks(l, n):
     n = max(1, n)     n = max(1, n)
     return [l[i:i + n] for i in range(0, len(l), n)]     return [l[i:i + n] for i in range(0, len(l), n)]
-</code>+~~~
  
 ------------- -------------
  
-== Determine if variable is defined in Python+## Determine if variable is defined in Python
  
 http://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python http://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python
  
-<code python>+~~~python
 try: try:
   thevariable   thevariable
Ligne 64: Ligne 81:
 else: else:
   print "sure, it was defined."   print "sure, it was defined."
-</code>+~~~
  
 I think it's better to avoid the situation. It's cleaner and clearer to write: I think it's better to avoid the situation. It's cleaner and clearer to write:
  
-<code python>+~~~python
 a = None a = None
 if condition: if condition:
     a = 42     a = 42
-</code>+~~~
  
 ------------ ------------
  
-== Getting file size in Python+## Getting file size in Python
  
 http://stackoverflow.com/questions/6591931/getting-file-size-in-python http://stackoverflow.com/questions/6591931/getting-file-size-in-python
  
-<code python>+~~~python
 def get_Size(file): def get_Size(file):
     file.seek(0,2) # move the cursor to the end of the file     file.seek(0,2) # move the cursor to the end of the file
     size = file.tell()     size = file.tell()
     return size     return size
-</code>+~~~
  
 Exemple : Exemple :
-<code python>+~~~python
 with open('plop.bin','rb') as file: with open('plop.bin','rb') as file:
     size=get_Size(file)     size=get_Size(file)
Ligne 98: Ligne 115:
         msg.append(un)         msg.append(un)
         msg.append(deux)         msg.append(deux)
-</code>+~~~
  
  
 ''/dev/null'' ''/dev/null''
-<code bash>+~~~python
 fnull = open(os.devnull, 'w') fnull = open(os.devnull, 'w')
-</code>+~~~
  
 ----------------- -----------------
  
-== Message d'erreur +## Message d'erreur 
  
 How to print to stderr in Python? How to print to stderr in Python?
Ligne 114: Ligne 131:
 http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python
  
-<code bash>+~~~python
 def warning(*objs): def warning(*objs):
-    print(*objs, file=sys.stderr +    print(*objs, file=sys.stderr) 
-</code>+~~~
  
-== Conversion hexa+## Conversion hexa
  
-<code python+~~~python 
 import numpy as np import numpy as np
  
Ligne 145: Ligne 162:
 "{0:8b}".format(int("a",16))    # '    1010' "{0:8b}".format(int("a",16))    # '    1010'
  
-</code>+~~~
  
 http://stackoverflow.com/questions/16843108/how-to-read-a-hex-file-into-numpy-array http://stackoverflow.com/questions/16843108/how-to-read-a-hex-file-into-numpy-array
-<code python>+~~~python
 with open(myfile) as f: with open(myfile) as f:
     iv = binascii.unhexlify(f.readline().strip())     iv = binascii.unhexlify(f.readline().strip())
Ligne 154: Ligne 171:
     count = int(f.readline())     count = int(f.readline())
     a = np.fromiter((binascii.unhexlify(line.strip()) for line in f), dtype='|S16')     a = np.fromiter((binascii.unhexlify(line.strip()) for line in f), dtype='|S16')
-</code>+~~~
  
  
-<code python>+~~~python
 hashlib.sha512('Bonjour'.encode('utf-8')).hexdigest() hashlib.sha512('Bonjour'.encode('utf-8')).hexdigest()
 hex(int.from_bytes('Bonjour'.encode('utf-8'), 'big')) hex(int.from_bytes('Bonjour'.encode('utf-8'), 'big'))
-</code>+~~~
  
 -------- --------
Ligne 166: Ligne 183:
 Créer un Dictionnaire à partir de deux listes (l'une clef, l'autre valeur) Créer un Dictionnaire à partir de deux listes (l'une clef, l'autre valeur)
  
-<code bash>+~~~python
 clef = ['a', 'b', 'c'] clef = ['a', 'b', 'c']
 valeur = [1, 2, 3] valeur = [1, 2, 3]
 dictionnaire=dict(zip(clef, valeur)) dictionnaire=dict(zip(clef, valeur))
-</code>+~~~
  
-== Test+## Test
  
 Voir : Voir :
Ligne 178: Ligne 195:
 * unittest * unittest
  
-== Exception+## Exception
  
 http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python
  
-<code python>+~~~python
 try: try:
     s        s   
Ligne 189: Ligne 206:
 else: # If no exception occured, do : else: # If no exception occured, do :
     s.user.logout()     s.user.logout()
-</code>+~~~
  
  
  
-== Temps / time+## Temps / time
  
 Voir : Voir :
 * timeit * timeit
  
-<code python>+~~~python
 start = time.time() start = time.time()
 UnifiedJob.objects.filter(id=1096679).update(status='canceled') UnifiedJob.objects.filter(id=1096679).update(status='canceled')
Ligne 204: Ligne 221:
  
 print(end - start) print(end - start)
-</code>+~~~
  
-== Strings+## Strings
  
 https://zerokspot.com/weblog/2015/12/31/new-string-formatting-in-python/ https://zerokspot.com/weblog/2015/12/31/new-string-formatting-in-python/
  
-== Debug+## Debug
  
 Source : https://www.geekarea.fr/wordpress/?p=763 Source : https://www.geekarea.fr/wordpress/?p=763
  
 Level 1 Level 1
-<code python>+~~~python
 f = open('/tmp/debug','a') f = open('/tmp/debug','a')
 f.write(variable + '\n') f.write(variable + '\n')
 f.close() f.close()
-</code>+~~~
  
 Level 2 Level 2
-<code python>+~~~python
 from pprint import pprint from pprint import pprint
 pprint(variable.__class__.__name__, f) pprint(variable.__class__.__name__, f)
 pprint(dir(variable), f) pprint(dir(variable), f)
 pprint(vars(variable), f) pprint(vars(variable), f)
-</code>+~~~
  
 Level 3 (sur une exception) Level 3 (sur une exception)
-<code python>+~~~python
 import traceback import traceback
 f.write(str(traceback.format_exc())) f.write(str(traceback.format_exc()))
-</code>+~~~
  
  
-== map reduce filter+## map reduce filter
  
 Voir :  Voir : 
Ligne 242: Ligne 259:
  
  
-== Aures+## Aures
  
 A noter que sur RedHat 8 le chemin vers python est ''/usr/libexec/platform-python'' A noter que sur RedHat 8 le chemin vers python est ''/usr/libexec/platform-python''
  
tech/python-draft.1744723975.txt.gz · Dernière modification : de Jean-Baptiste

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki