I've been writing code all my life, but I've never mastered the essence of coding. In most cases, use visual Basic because I am most comfortable with VB. Also a little bit about other languages (R, C, JavaScript, Applescript, hypertext, and Basic in 1979). A few years ago, I decided to use Python only to improve my coding ability. Many wheels were invented repeatedly in the process, but I didn't mind because I enjoyed the fun of solving the problem. At the same time, it is sometimes possible to discover more efficient, Python-style solutions. After a long time, there will be a moment of epiphany, realizing that there is no need to deal with problems in difficult and lengthy ways. Here's a list of 10 python usages that might save a lot of time if I found out earlier.
There are no list derivations and lambda functions. Both of these usages are python, efficient and cool, but because they are often encountered in StackOverflow or elsewhere, it is important to learn python to know these two things. There are also no ternary operators, adorners, and generators, because I rarely use them.
This article also has a Ipython notebook nbviewer version.
1. Using python 3 output in Python 2
Python 2 is incompatible with Python 3, which makes me not sure which version of Python to choose. Eventually I chose Python 2 because many of the libraries I needed were not compatible with Python 3.
In practice, however, the biggest version difference in everyday use is output (print) and division behavior. Now I use the import from future in the Python 2 code to import the Python 3 output and division. Almost all of the libraries I use now support Python 3, so they migrate to Python 3 very quickly.
MyNumber = 5
print "Python 2:"
print "The number is%d"% (mynumber)
print MYNUMBER/2,
print MyNumber// 2 from
__future__ import print_function from
__future__ Import Division
print (' Npython 3: ')
print (" The number is {} ". Format (mynumber))
print (MYNUMBER/2, end= ')
print (MyNumber//2)
Python 2: The
nu Mber is 5
2 2
Python 3: The # is 5 2.5-
2
Yes, for C-series developers who prefer parentheses over indentation, here's an Easter egg:
From __future__ import braces
File "", line 1 from
__future__ import braces
syntaxerror:not a chance
2. Enumerate (list)
Obviously, when iterating a list, you should iterate over both the elements and their indexes, but for a long time, I'm embarrassed to use count variables or slices.
MyList = ["It S", ' only ', ' a ', ' model '] for
index, item in enumerate (mylist):
print (index, item)
0 It ' S
1 only
2 a
3 model
3. Chain comparison operator
Since I used to be a static language (which has two meanings in these languages), I never put two comparison operators in an expression. In many languages, 4 > 3 > 2 returns false because the result of 4 > 3 is a Boolean value, and True > 2 results in False.
MyNumber = 3
if 4 > MyNumber > 2:
print ("Chained comparison operators work! N "* 3)
Chained comparison operators work!
Chained comparison operators work!
Chained comparison Operators work!
4. Collections. Counter
Python's collection library seems to be the best. When calculating the number of elements in a collection, the answer StackOverflow found was to create an ordered dictionary, but I persisted in using a code fragment to create a dictionary to calculate how often the elements in the results would appear. Until one day, I found that I could use collections.deque.
From collections import Counter from
random import randrange
import pprint
mycounter = Counter ()
For I in range (m):
Random_number = Randrange (Ten)
Mycounter[random_number] + = 1 for
i in range (10):
print (i, mycounter[i])
0
1
2
3 6 4
6 5 (6 7) 8 9 8
5. Dictionary derivation
One of the key symbols of Python developers is understanding list derivation, but eventually I found that dictionary derivation is also useful, especially when exchanging the keys and values of a dictionary.
My_phrase = ["No", "one", "expects", "the", "Spanish", "inquisition"]
my_dict = {Key:value for value, key in Enumera Te (my_phrase)}
print (my_dict)
reversed_dict = {Value:key for key, value in My_dict.items ()}
print ( REVERSED_DICT)
{' inquisition ': 5, ' No ': 0, ' expects ': 2, ' one ': 1, ' Spanish ': 4, ' the ': 3}
{0: ' No ', 1: ' One ', 2: ' Expects ', 3: ' The ', 4: ' Spanish ', 5: ' Inquisition '}
6. Execute shell command with subprocess
Before, I used the OS library to invoke external commands to process files, and now I can perform video editing in Python with complex commands such as ffmpeg in a coded way.
(Yes, I and my clients all use Windows, if you despise me for this, I will be generous to accept!) )
Note that using the OS library to complete this particular command is better than using subprocess. I just want to have a command that everyone is familiar with. At the same time, in general, it is a bad idea to use the Shell=true parameter in subprocess, where this parameter is used only to place the output of the command in a Ipython notebook cell. Do not use this parameter yourself!
Import subprocess
output = subprocess.check_output (' dir ', shell=true)
print (output)
Volume in drive C are OS Volume serial number is [redacted] Directory of c:usersdaviddocuments[redacted] 2014-11-26 06:0
4 AM <DIR>.
2014-11-26 06:04 AM <DIR>. 2014-11-23 11:47 am <DIR> git 2014-11-26 06:06 am <DIR> ipynb_checkpoints 2014-11-23 08:59 am ;D ir> CCCMA 2014-09-03 06:58 am 19,450 colorbrewdict.py 2014-09-03 06:58 AM 92,175 IMAGECOMPARE.IPYNB 201 4-11-23 08:41 AM <DIR> japan_earthquakes 2014-09-03 06:58 am 1,100 LICENSE 2014-09-03 06:58 am 5,26 3 MONTY_MONTE.IPYNB 2014-09-03 06:58 am 31,082 pocket_tumblr_reddit_api.ipynb 2014-11-26 06:04 AM 3,211 README. MD 2014-11-26 06:14 am 19,898 top_10_python_idioms.ipynb 2014-09-03 06:58 AM 5,813 Tree_convert_mega_to_gexf.ip YNB 2014-09-03 06:58 am 5,453 tree_convert_mega_to_json.ipynb 2014-09-03 06:58 AM 1,211 tree_convert_newick_to _json.py 2014-09-03 06:58 AM 55,970 weather_ml.ipynb File (s) 240, 626 bytes 6 Dir (s) 180,880,490,496 bytes free
7. The dictionary. Get () and. Iteritems () method
The dictionary's Get () method can set a default value, which is useful when the default value parameter in the method is returned when the key found with get () does not exist. As with enumerate () in the list, you can iterate through the elements in the dictionary with the key-value tuple.
my_dict = {' name ': ' Lancelot ', ' Quest ': ' Holy Grail ', ' favourite_color ': ' Blue '}
print (My_dict.get (' airspeed Velocity of a unladen swallow ', ' African or european?n ')
for key, value in My_dict.iteritems ():
print (key, value , sep= ":")
African or European?
Quest:holy Grail
name:lancelot
favourite_color:blue
8. Tuple unpack for exchanging elements
In VB, whenever you need to exchange two variables, use a silly temporary variable: c = A; A = b; B = C
A = ' Spam '
b = ' Eggs '
print (A, b)
A, B = B, a
print (A, b)
Spam Eggs
Eggs Spam
9. Introspection Tool Introspection Tools
I know the Dir () method, and I thought the Help () method was the same as the Magic command in Ipython, but help () was more powerful.
My_dict = {' That ': ' A ex-parrot! '} Help (my_dict)
Help on Dict object:class dict (object) | Dict ()-> New Empty Dictionary | Dict (mapping)-> new dictionary initialized from a mapping object ' s | (key, value) pairs | Dict (iterable)-> new dictionary initialized as if via: | d = {} | For K, v. in iterable: | D[k] = v | Dict (**kwargs)-> new dictionary initialized with the Name=value pairs | In the keyword argument list.
For Example:dict (one=1, two=2) | |
Methods defined here: | |
__cmp__ (...) |
x.__cmp__ (y) <==> cmp (x,y) | |
__contains__ (...) |
D.__contains__ (k)-> True if D has a key k, else False | |
__delitem__ (...) |
x.__delitem__ (y) <==> del x[y] | |
__eq__ (...) |
x.__eq__ (y) <==> x==y |
[truncated for spaces] | |
Update (...) | D.update ([E,]**f)-> None.
Update D from Dict/iterable E and F. | If E present and has a. Keys () method, Does:for k in e:d[k] = E[k] | If E present and lacks. Keys () method, Does:for (K, v) in e:d[k] = v | In either case, this is foLlowed by:for k in f:d[k] = F[k] | |
VALUES (...) |
D.values ()-> list of D ' s values | |
Viewitems (...) |
D.viewitems ()-> a Set-like object providing a view on D ' s items | |
Viewkeys (...) |
D.viewkeys ()-> a Set-like object providing a view on D ' s keys | |
Viewvalues (...) |
D.viewvalues ()-> an object providing a view on D ' s values | | ----------------------------------------------------------------------
|
Data and other attributes defined: | |
__hash__ = None | | __new__ = |
t.__new__ (S, ...)-> a new object with type S, a subtype of T
PEP-8 compatible string concatenation
PEP8 is a Python coded style guide. Aside from the others, PEP8 requires that each line not be more than 80 characters, and that more than one part of the line should be wrapped and indented.
Wrapping can be done with a backslash, a comma, a parenthesis "()", or an extra plus "+". But for multi-line strings, these solutions are not elegant enough. Python has a multiline string notation, that is, three quotes, but this cannot be wrapped and remains indented.
There is another way, that is, parentheses with no commas. I don't know why I can work this way, but I can do it.
My_long_text = ("We are no longer the Knights who say ni!"
" We are now the Knights who say ekki-ekki-"Ekki-p ' tang-zoom-boing-z ' nourrwringmm!
")
Print (My_long_text)
We are no longer the Knights who say ni! We are now the Knights who say Ekki-ekki-ekki-p ' tang-zoom-boing-z ' nourrwringmm!