10 basic python usages that are easily overlooked but should be mastered

Source: Internet
Author: User
Tags iterable
I've been writing code all my life, but I've never mastered the essence of coding. Most of the cases use visual Basic, because I am most comfortable with VB. Learn a little bit about other languages (R, C, JavaScript, Applescript, hypertext, and Basic for Learning in 1979). A few years ago, I decided to use Python only to improve my coding skills. A lot of wheels were invented in the process, but I don't mind because I enjoy the fun of solving problems. At the same time, more efficient, Python-style solutions can be found. After a long time, there will be moments of Epiphany, aware that there is no need to deal with problems in a difficult and lengthy way. 10 python usages are listed below, and if I find out earlier, it might save a lot of time.

There are no list derivations and lambda functions. Although these two usages are Python-style, high efficiency is very cool, but because often encountered in StackOverflow or other places, so learn python should know these two things. There are also no ternary operators, adorners, and generators, because I seldom use them.

This article also has a Ipython notebook nbviewer version.
1. Using Python 3-style output in Python 2

Python 2 is not compatible with Python 3, which lets me not know which version of Python to choose. I finally chose Python 2, because many of the libraries I needed were incompatible with Python 3.

In practice, however, the largest version difference in daily use is output (print) and division behavior. Now I import the output and division of Python 3 with import from the future in Python 2 's code. Almost all of the libraries I've used now support Python 3, so I'm migrating to Python 3 very quickly.

MyNumber = 5 print "Python 2:" Print "The number is%d" percent (mynumber) print Mynumber/2,print MyNumber//2 from __future__ Import print_functionfrom __future__ Import Division print (' Npython 3: ') print ("The number is {}". Format (mynumber)) print (MYNUMBER/2, end= ") print (MyNumber//2) Python 2:the number is a 2 python 3:the number is 52.5 2

Yes, for C-series developers who prefer parentheses to indentation, there is also an egg:

From __future__ import Bracesfile "", line 1from __future__ import Bracessyntaxerror:not a chance

2. Enumerate (list)

Obviously, when iterating over a list, you should iterate over the elements and their indexes at the same time, but for a long time, I've been embarrassed with counting variables or slices.

MyList = ["It ' s", ' only ', ' a ', ' model '] for index, item in enumerate (mylist):  print (index, item) 0 It ' S1 only2 a3 mode L

3. Chained comparison operators

Since I used static languages (which have two semantics 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 will produce 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 looks the best. When calculating the number of elements in the collection, StackOverflow found the answer is to create an ordered dictionary, but I insisted on using a code snippet to create a dictionary to calculate the frequency of occurrences of the elements in the result. Until one day, I found that I could use collections.deque.

From collections import Counterfrom random import randrangeimport pprint mycounter = Counter () for I in range:  RA Ndom_number = Randrange (Ten)  Mycounter[random_number] + = 1 for i in range (10):  

0 101 102 133 64 65 116 107 148 129 8

5. Dictionary derivation

An important sign of Python developers is understanding the list derivation, but in the end I find that dictionary derivation is also useful, especially when exchanging dictionary keys and values.

My_phrase = ["No", "one", "expects", "the", "Spanish", "inquisition"]my_dict = {Key:value for value, key in enumerate (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 commands with subprocess

Previously, I used the OS library to invoke external commands to process files, and now I can do video editing with complex commands such as ffmpeg in Python in a coded fashion.

(Yes, my clients and I use Windows, and if you despise me, I will accept it generously!) )

Note that it is better to complete this particular command with the OS library than with subprocess. I just want to have a command that everyone is familiar with. At the same time, in general, using the Shell=true parameter in subprocess is a very bad idea, and this parameter is used here only to be able to place the output of the command in a Ipython notebook cell. Do not use this parameter yourself!

Import subprocessoutput = Subprocess.check_output (' dir ', shell=true) print (output)

Volume in drive C was osvolume Serial number is [Redacted]directory of c:usersdaviddocuments[redacted] 2014-11-26 06:04 AM
 
  
   . 2014-11-26 06:04 AM 
   
    .  
    2014-11-23 11:47 am 
    
     . git2014-11-26 06:06 am 
     
      . ipynb_checkpoints2014-11-23 08:59 am 
      
       cccma2014-09-03 06:58 am 19,450 colorbrewdict.py2014-09-03 06:58 am 92,175 imagecompare.ipynb20 14-11-23 08:41 am 
       
        japan_earthquakes2014-09-03 06:58 am 1,100 license2014-09-03 06:58 am 5,263 Monty_mon te.ipynb2014-09-03 06:58 am 31,082 pocket_tumblr_reddit_api.ipynb2014-11-26 06:04 am 3,211 README.md2014-11-26 06:14 am 1 9,898 top_10_python_idioms.ipynb2014-09-03 06:58 am 5,813 tree_convert_mega_to_gexf.ipynb2014-09-03 06:58 am 5,453 Tree _convert_mega_to_json.ipynb2014-09-03 06:58 am 1,211 tree_convert_newick_to_json.py2014-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. Get () and. Iteritems () Methods of the dictionary

The Get () method of the dictionary can set the default value, and it is useful to return the default value parameter in a method when the key found with Get () is not present. As with enumerate () in the list, you can iterate over the elements in the dictionary with a key-value tuple.

my_dict = {' name ': ' Lancelot ', ' Quest ': ' Holy Grail ', ' favourite_color ': ' Blue '} print (My_dict.get (' airspeed velocity of a n Unladen Swallow ', ' African or European?n ')) for key, value in My_dict.iteritems ():  print (key, value, sep= ":") afric An OR European? Quest:holy Grailname:Lancelotfavourite_color:blue

8. Tuple unpacking for exchanging elements

In VB, every time you need to exchange two variables, you have to 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 Eggseggs Spam

9. Introspection Tool Introspection Tools

I know the Dir () method, I thought the Help () method is the same as the Magic command in Ipython, but the function of help () is 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 SPACE] | | 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 () A object providing a view on D ' s values | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None | | __new__ = | T.__NEW__ (S, ...)-A new object with type S, a subtype of T

PEP-8-compatible string connections

PEP8 is a guide to Python coding styles. Aside from the rest, PEP8 requires that each line cannot exceed 80 characters, and that the part that exceeds the line is wrapped and indented.

Line breaks can be done with backslashes, a comma "," parenthesis "()", or an additional plus "+". But for multi-line strings, these solutions are not elegant. Python has a multi-line string notation, which is three quotation marks, but it does not wrap and then remains indented.

There is another way, that is, parentheses without commas. I don't know why I can work this way, but I can use it.

My_long_text = ("We is 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 is no longer the Knights who say ni! We are now the Knights who say Ekki-ekki-ekki-p ' tang-zoom-boing-z ' nourrwringmm!
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.