Python: Difference between revisions

From LPTMS Wiki
Jump to navigation Jump to search
Line 32: Line 32:


== Tips ==
== Tips ==
* with '''pylab''', removes the white borders:
<source lang="py">
savefig('figure.eps',format='eps',bbox_inches="tight")
</source>


* equivalent of the C ternary operator ?: (''test'' ? ''restrue'' : 'resfalse''), use a tuple is possible but not transparent
* equivalent of the C ternary operator ?: (''test'' ? ''restrue'' : 'resfalse''), use a tuple is possible but not transparent

Revision as of 16:29, 15 September 2015

Documentation

Libraries and softwares

Miscellaneous

Tips

  • with pylab, removes the white borders:

<source lang="py"> savefig('figure.eps',format='eps',bbox_inches="tight") </source>

  • equivalent of the C ternary operator ?: (test ? restrue : 'resfalse), use a tuple is possible but not transparent

<source lang="py"> (resfalse,restrue)[test] </source> prefer the inline condition testing way <source lang="py"> res = restrue if test or resfalse

  1. example

min = lambda x,y: x if x<y else y min(1,2) </source>

  • adding a path to a directory containing your module files

<source lang="py"> import sys sys.path += [ "/home/username/bin/Python" ] </source>

  • test whether a string has only digits or letters

<source lang="py"> str = '1321' str.isdigit() # returns True/False str.isalpha() # returns True/False </source>

  • Nested for loops in a single line:

<source lang="py"> for n,m in [ (n,m) for n in range(10) for m in range(2) ]:

   print n,m

</source>