Fonctions utiles (Python)
Sommaire |
List
Le dernier élément d'une liste
someList[-1]
Supprimer le contenu d'une liste
Problème:
>>> tooLongNameShotList = [<__main__.Shot instance at 0xf55638>, <__main__.Shot instance at 0xf55680>, <__main__.Shot instance at 0xf556c8>] >>> curShotList = tooLongNameShotList # create a new reference for the list >>> curShotList = [] >>> curShotList [] # you think you have empty the list? >>> tooLongNameShotList # but you create a new (empty) list actually and you have not changed the original one... [<__main__.Shot instance at 0xf55638>, <__main__.Shot instance at 0xf55680>, <__main__.Shot instance at 0xf556c8>]
Solution:
>>> tooLongNameShotList = [<__main__.Shot instance at 0xf55638>, <__main__.Shot instance at 0xf55680>, <__main__.Shot instance at 0xf556c8>] >>> curShotList = tooLongNameShotList # create a new reference for the list >>> del curShotList[:] # this mean: del every instance of the list. >>> curShotList [] >>> tooLongNameShotList [] # The two lists are empty, you didn't break reference.
En bref: </syntaxhighlight> del myList[:] </syntaxhighlight>
Supprimer les items d'une liste durant son itération
somelist = [x for x in somelist if isOk(x)]
En fait, créé une nouvelle liste (qui écrase la première) en se servant d'un filtre (x for x in list if condition).
Source: http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python
Afficher, via print, un attribut de chaque objet d'une list
Quand on souhaite afficher une liste d'objet python, il peut être ennuyeux d'avoir la représentation suivante:
print [shotList] >>> [<__main__.Shot instance at 0xf55638>, <__main__.Shot instance at 0xf55680>, <__main__.Shot instance at 0xf556c8>]
L'astuce consiste a afficher un seul (ou plusieurs) attributs de chaque objet. Vous aurez alors quelque chose sous une forme beaucoup plus lisible:
print [shot.seq+"-"+shot.name for shot in shotList] >>> ["S010-P0140", "S010-P0141", "S010-P0142"]
Générer une liste remplie de N éléments
>>> [None]*10 [None, None, None, None, None, None, None, None, None, None]
Lister les dossiers/fichiers d'un dossier
import os myPath = "/a/path/to/dine/in/hell" if not os.path.isdir( myPath ) : raise Exception( "Not a valid directory -> %s" % myPath ) # go through each encoutered element in the folder for entry in os.listdir( myPath ) : # join to create a valid path curPath = os.path.join( myPath, entry ) # check the path is a file if os.path.isfile( curPath ) : print "This is a file -> %s" % curPath elif os.path.isdir( curPath ) : print "This is a folder -> %s" % curPath else : print "Don't know what is it -> %s" % curPath
Générer une chaîne de caractères aléatoires
Très pratique pour générer des fichiers temporaires.
Utilise random.choice.
import random randomStr = "" for i in range(50): randomStr += random.choice("abcdef0123456789") print randomStr # "7430db916980163e27ea89d07819282cff10a4db023dd1b569"
Printer la ligne en court
import inspect # renvoit la ligne du programme en court inspect.currentframe().f_back.f_lineno
Source: Grabbing the current line number easily (Python recipe)
Écrire dans un fichier
myFile = open(filePath, "w") myFile.write(inputList[i]) myFile.close()
Lire un fichier ligne a ligne
myFile = open(filePath,"r") for line in myFile.readlines() : print line myFile.close()
Modules
Lister les modules disponibles
>>> help() help> modules Please wait a moment while I gather a list of all available modules...
Module dans un module dans un...
Soit la structure suivante:
testPythonFolder/
subOne/
__init__.py
subTwoo/
__init__.py
testouille.py
helloWorld()On récupère les modules comme ça:
>>> import subOne.subTwoo >>> import subOne.subTwoo.testouille >>> subOne.subTwoo.testouille.helloWorld() hello world >>>
Fonctionnement des modules dans un module
Importer un module en string
moduleOne = __import__('moduleOne')
Source: Importing Python Modules
Définir un PYTHONPATH et appeler un module directement
Cela se fait depuis sys.path:
>>> import amodule Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named amodule >>> import sys >>> sys.path.append('/path/to/a/module') >>> import amodule
Module re
Faire une recherche en case insensitive
En utilisant compile
>>> s = 'TeSt' >>> casesensitive = re.compile('test') >>> ignorecase = re.compile('test', re.IGNORECASE) >>> print casesensitive.match(s) None >>> print ignorecase.match(s) <_sre.SRE_Match object at 0x02F0B608>
En utilisant search et match
>>> re.search('test', 'TeSt', re.IGNORECASE) >>> re.match('test', 'TeSt', re.IGNORECASE)
En utilisant sub
Il faut ajouter (?i) au début du pattern.
>>> re.sub("maya", "test", "maya-MAYA-MaYa-Maya-mm",) 'test-MAYA-MaYa-Maya-mm' >>> re.sub("(?i)maya", "test", "maya-MAYA-MaYa-Maya-mm",) 'test-test-test-test-mm'
Module multiprocessing
L’interpréteur Python n’étant pas thread safe, le multiprocessing lance N Python (ou N est le nombre de core).
Utiliser Pool.map_async()
Ce code utilise bien tout les cores disponible.
import time import multiprocessing as mp K = 50 def costlyFunction(z): result = 0 for k in xrange(1, K+2): result += z ** (1 / k**1.5) return result curtime = time.time() pool = mp.Pool() asyncResult = pool.map_async(costlyFunction, (i for i in xrange(1000000))) resultSum = sum(asyncResult.get()) # asyncResult.get() is a list of resulting values print resultSum print "time elapsed:", time.time() - curtime
500172313292.0 time elapsed: 9.4265730381
Source: multiprocessing.Pool example
Liens
Module functools
Permet de créer une fonction (un pointeur sur fonction) a partir d'une autre combiné a ces arguments.
import functools def maFonction(text): print text pointerToCommand = functools.partial(maFonction, "argument!") pointerToCommand() # print "argument!"
PyQt
Supprimer tout les widget d'un layout
layout = myWidget.layout() while layout.count() > 0: item = layout.takeAt(0) if not item: continue widget = item.widget() if widget: widget.deleteLater()
Liens
- Python snippets par sebsauvage.