10 basic Python usage that is easy to ignore but should be mastered, 10 ignore python usage

Source: Internet
Author: User
Tags iterable

10 basic Python usage that is easy to ignore but should be mastered, 10 ignore python usage
I have been writing code all my life, but I have never mastered the essence of code. In most cases, Visual Basic is used because I use VB most comfortably. I also learned a little about other languages (R, C, JavaScript, Applescript, Hypertext, and basic I learned in 1979 ). A few years ago, I decided to use only Python to improve my coding capability. I have repeatedly invented many wheels in this process, but I don't mind because I have fun solving problems. At the same time, you can find more effective and Python-based solutions. After a long time, there will be an epiphany, realizing that there is no need to deal with the problem in a difficult and lengthy way. The following lists 10 Python usages. If I find it earlier, it may save a lot of time.

There is no list Derivation or lambda function here. Although these two methods are both Python-based and highly efficient and cool-looking, we should know these two things when learning Python because they are often used in StackOverflow or elsewhere. At the same time, there are no ternary operators, decorators, and generators, Because I rarely use them.

This article also provides an IPython notebook nbviewer version.
1. Use Python 3 output in Python 2

Python 2 is incompatible with Python 3, which makes it hard for me to know which version of Python to choose. Finally, I chose Python 2 because many of the databases I needed at that time were incompatible with Python 3.

But in fact, the biggest version difference in daily use is the output (print) and Division behavior. Now I use import from future in Python 2 code to import the output and division of Python 3. Almost all databases I use now support Python 3, so it will soon be migrated to Python 3.
 

mynumber = 5 print "Python 2:"print "The number is %d" % (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 52 2 Python 3:The number is 52.5 2

By the way, for developers who prefer parentheses rather than indentation in C series, there is also an egg:
 

from __future__ import bracesFile "", line 1from __future__ import bracesSyntaxError: not a chance

2. enumerate (list)

Obviously, during the iteration list, the elements and their indexes should be iterated at the same time, but for a long time, I am embarrassed to use counting variables or slices.
 

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

3. chained comparison Operators

Since I used static languages (which have the ambiguity in these languages), I have never put two comparison operators in one expression. In many languages, 4> 3> 2 returns False, because 4> 3 returns a Boolean value, while True> 2 returns 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

The collection library of Python looks like the best. When calculating the number of elements in a collection, StackOverflow finds the answer to creating an ordered dictionary, but I insist on using a code snippet to create a dictionary and calculate the frequency at which the elements appear in the result. Until one day, I found that collections. deque can be used.
 

from collections import Counterfrom random import randrangeimport pprint mycounter = Counter() for i in range(100):  random_number = randrange(10)  mycounter[random_number] += 1 for i in range(10):  print(i, mycounter[i]) 
0 101 102 133 64 65 116 107 148 129 8

5. dictionary Derivation

An important symbol for Python developers is understanding list derivation, But I found 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. Use subprocess to execute shell commands

In the past, I used the OS library to call external commands to process files, but now I can use Python to encode complex commands such as ffmpeg for video editing.

(Yes, my customers and I both use Windows. If you despise me, I will accept it generously !)

Note: it is better to use the OS library to complete this specific command than to use subprocess. I just want to have a command that everyone is familiar. At the same time, it is a bad idea to use the shell = True parameter in subprocess. Here, this parameter is only used to place command output in an IPython notebook unit. Do not use this parameter by yourself!
 

import subprocessoutput = subprocess.check_output('dir', shell=True)print(output)
Volume in drive C is OSVolume Serial Number is [REDACTED]Directory of C:UsersDavidDocuments[REDACTED] 2014-11-26 06:04 AM  <DIR>     .2014-11-26 06:04 AM  <DIR>     ..2014-11-23 11:47 AM  <DIR>     .git2014-11-26 06:06 AM  <DIR>     .ipynb_checkpoints2014-11-23 08:59 AM  <DIR>     CCCma2014-09-03 06:58 AM      19,450 colorbrewdict.py2014-09-03 06:58 AM      92,175 imagecompare.ipynb2014-11-23 08:41 AM  <DIR>     Japan_Earthquakes2014-09-03 06:58 AM       1,100 LICENSE2014-09-03 06:58 AM       5,263 monty_monte.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      19,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       11 File(s)    240,626 bytes        6 Dir(s) 180,880,490,496 bytes free

7. dictionary. get () and. iteritems () Methods

You can set the default value for the get () method of the dictionary. If the key found by get () does not exist, the default value parameter in the return method is useful. Like enumerate () in the list, you can use key-value tuples to iterate the elements in the dictionary.
 

my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'} print(my_dict.get('airspeed velocity of an unladen swallow', 'African or European?n')) for key, value in my_dict.iteritems():  print(key, value, sep=": ") African or European? quest: Holy Grailname: Lancelotfavourite_color: blue

8. unpackage the tuples used for element exchange

In VB, Every time two variables need to be exchanged, a stupid temporary variable is required: 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 tools

I know the dir () method. I thought it was in the help () method and IPython? Magic commands are the same, but help () is more powerful.
 

my_dict = {'That': 'an 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() -> an 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

10. PEP-8 compatible string connection

PEP8 is the Python coding style guide. Aside from others, PEP8 requires that each line contain no more than 80 characters, and the excess part should be wrapped and indented.

You can use a backslash, a comma (,) or an additional plus sign (+) to wrap the line. But these solutions are not elegant enough for multiline strings. Python has a multi-line string mark, that is, three quotation marks, but this prevents indentation after line breaks.

There is another method, that is, parentheses without commas. I don't know why it works in this way, but it does.
 

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!

 

Related Article

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.