18 Efficient Python Programming Tips

Click the "Little White Learns Vision" above, select "Star" or "Top"
Heavy content, delivered first time

Initially getting to know Python, I felt that Python met all my requirements for a programming language during school. The efficient programming techniques of Python make us, who suffered through four years of C or C++, extremely excited, finally liberated. If a high-level language can’t do this, what’s the point of being high-level?

01 Swap Variables

>>>a=3

>>>b=6

If you want to swap variables in C++, you definitely need an empty variable. But Python doesn’t require this, just one line, everyone pay attention

>>>a,b=b,a

>>>print(a)>>>6

>>>print(b)>>>3

02 Dictionary Comprehensions and Set Comprehensions

Most Python programmers know and have used list comprehensions. If you are not very familiar with the concept of list comprehensions—a list comprehension is a shorter and more concise way to create a list.

>>> some_list = [1, 2, 3, 4, 5]

>>> another_list = [ x + 1 for x in some_list ]

>>> another_list
[2, 3, 4, 5, 6]

Since Python 3.1, we can use the same syntax to create sets and dictionaries:

>>> # Set Comprehensions
>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]

>>> even_set = { x for x in some_list if x % 2 == 0 }

>>> even_set
set([8, 2, 4])

>>> # Dict Comprehensions

>>> d = { x: x % 2 == 0 for x in range(1, 11) }

>>> d
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

In the first example, we created a set with unique elements based on some_list, and the set only contains even numbers. In the dictionary example, we created a key that is unique integers between 1 and 10, and the value is a boolean indicating whether the key is even.

Another thing worth noting is the literal representation of sets. We can simply create a set using this method:

>>> my_set = {1, 2, 1, 2, 3, 4}

>>> my_set
set([1, 2, 3, 4])

Without needing to use the built-in set() function.

03 Using Counter for Counting

This seems obvious, but is often forgotten. Counting something is a common task for most programmers, and in most cases, it is not very challenging—here are a few ways to accomplish this task more simply.

Python’s collections library has a built-in subclass of the dict class that is specifically designed for this:

>>> from collections import Counter
>>> c = Counter('hello world')

>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})

>>> c.most_common(2)
[('l', 3), ('o', 2)]

04 Pretty Print JSON

JSON is a very good form of data serialization, widely used by various APIs and web services today. Using Python’s built-in JSON processing can make JSON strings somewhat readable, but when dealing with large data, it can appear as a long, continuous line, making it difficult for the human eye to read.

To make JSON data more user-friendly, we can use the indent parameter to output pretty JSON. This is especially useful when programming interactively in the console or logging:

>>> import json

>>> print(json.dumps(data))  # No indentation
{"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]}

>>> print(json.dumps(data, indent=2))  # With indentation

{
  "status": "OK",
  "count": 2,
  "results": [

    {
      "age": 27,
      "name": "Oz",
      "lactose_intolerant": true
    },
    {
      "age": 29,
      "name": "Joe",
      "lactose_intolerant": false
    }
  ]
}

Similarly, using the built-in pprint module can also make anything else printed out look nicer.

05 Solving FizzBuzz

Recently, Jeff Atwood promoted a simple programming exercise called FizzBuzz, the problem is stated as follows:

Write a program that prints the numbers from 1 to 100. For multiples of 3, print “Fizz” instead of the number, for multiples of 5, print “Buzz”, and for numbers that are multiples of both 3 and 5, print “FizzBuzz”.

Here is a short, interesting way to solve this problem:

for x in range(1,101):
    print"fizz"[x%3*len('fizz')::]+"buzz"[x%5*len('buzz')::] or x

06 Inline if Statements

print "Hello" if True else "World"
>>> Hello

07 Concatenation

The last method here is very cool when binding two different types of objects.

nfc = ["Packers", "49ers"]
afс = ["Ravens", "Patriots"]
print nfc + afc
>>> ['Packers', '49ers', 'Ravens', 'Patriots']

print str(1) + " world"
>>> 1 world

print `1` + " world"
>>> 1 world

print 1, "world"
>>> 1 world
print nfc, 1
>>> ['Packers', '49ers'] 1

08 Numeric Comparison

This is an awesome and simple method that I have rarely seen in many languages.

x = 2
if 3 > x > 1:
   print x
>>> 2
if 1 < x > 0:
   print x
>>> 2

09 Iterating Two Lists Simultaneously

nfc = ["Packers", "49ers"]
afс = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
     print teama + " vs. " + teamb
>>> Packers vs. Ravens
>>> 49ers vs. Patriots

10 Iterating Lists with Index

teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
    print index, team
>>> 0 Packers
>>> 1 49ers
>>> 2 Ravens
>>> 3 Patriots

11 List Comprehensions

Given a list, we can filter out even numbers:

numbers = [1,2,3,4,5,6]
even = []
for number in numbers:
    if number%2 == 0:
        even.append(number)

Transform it into:

numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]

12 Dictionary Comprehension

Similar to list comprehensions, dictionaries can do the same work:

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print {key: value for value, key in enumerate(teams)}
>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}

13 Initializing List Values

items = [0]*3
print items
>>> [0,0,0]

14 Converting List to String

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print ", ".join(teams)
>>> 'Packers, 49ers, Ravens, Patriots'

15 Getting Elements from a Dictionary

I admit that try/except code is not elegant, but here is a simple method to try to look up a key in a dictionary, if not found, use the second parameter as its variable value.

data = {'user': 1, 'name': 'Max', 'three': 4}
try:
   is_admin = data['admin']
except KeyError:
   is_admin = False

Replace it with:

data = {'user': 1, 'name': 'Max', 'three': 4}
is_admin = data.get('admin', False)

16 Getting a Subset of a List

Sometimes, you only need a subset of elements from a list, here are some ways to get subsets of a list.

x = [1,2,3,4,5,6]
# First 3
print x[:3]
>>> [1,2,3]
# Middle 4
print x[1:5]
>>> [2,3,4,5]
# Last 3
print x[3:]
>>> [4,5,6]
# Odd items
print x[::2]
>>> [1,3,5]
# Even items
print x[1::2]
>>> [2,4,6]

In addition to Python’s built-in data types, the collections module also includes some special use cases, where Counter is very useful. If you participated in this year’s Facebook Hacker Cup, you might even find its practicality.

from collections import Counter
print Counter("hello")
>>> Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

17 Itertools

Similar to the collections library, there is also a library called itertools, which can efficiently solve certain problems. One use case is to find all combinations, which can tell you all the possible combinations of elements in a group.

from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
    print game
>>> ('Packers', '49ers')
>>> ('Packers', 'Ravens')
>>> ('Packers', 'Patriots')
>>> ('49ers', 'Ravens')
>>> ('49ers', 'Patriots')
>>> ('Ravens', 'Patriots')

18 False == True

Compared to practical techniques, this is a very interesting fact: in Python, True and False are global variables, so:

False = True
if False:
   print "Hello"
else:
   print "World"
>>> Hello
Good news! The "Little White Learns Vision" knowledge circle is now open to the public👇👇👇



Download 1: OpenCV-Contrib Extension Module Chinese Version Tutorial
Reply "Extension Module Chinese Tutorial" in the "Little White Learns Vision" public account backend to download the first Chinese version of the OpenCV extension module tutorial on the internet, covering installation of extension modules, SFM algorithms, stereo vision, target tracking, biological vision, super-resolution processing, etc., with more than twenty chapters of content.

Download 2: Python Vision Practical Projects 52 Lectures
Reply "Python Vision Practical Projects" in the "Little White Learns Vision" public account backend to download 31 practical vision projects including image segmentation, mask detection, lane line detection, vehicle counting, adding eyeliner, license plate recognition, character recognition, emotion detection, text content extraction, facial recognition, etc., to help quickly learn computer vision.

Download 3: OpenCV Practical Projects 20 Lectures
Reply "OpenCV Practical Projects 20 Lectures" in the "Little White Learns Vision" public account backend to download 20 practical projects based on OpenCV for advanced learning.

Discussion Group

Welcome to join the reader group of the public account to communicate with peers. Currently, there are WeChat groups for SLAM, 3D vision, sensors, autonomous driving, computational photography, detection, segmentation, recognition, medical imaging, GAN, algorithm competitions, etc. (will gradually be subdivided in the future). Please scan the WeChat ID below to join the group, with remarks: "Nickname + School/Company + Research Direction", for example: "Zhang San + Shanghai Jiao Tong University + Vision SLAM". Please follow the format for remarks, otherwise, you will not be approved. Once added successfully, you will be invited to related WeChat groups based on the research direction. Please do not send advertisements in the group, otherwise, you will be removed from the group. Thank you for your understanding~




Leave a Comment