Python Beginner Tutorial: 18 Efficient Programming Tips

关注👆公众号、回复「 python」领零基础教程!来源于网络,侵删

Getting acquainted with the Python language, you feel that Python meets all your requirements for a programming language from school. The efficient programming techniques in Python excite those who have spent four years learning C or C++, finally feeling liberated. If a high-level language can’t achieve this, what’s the point of being a high-level language?

01 Swap Variables

Python Beginner Tutorial: 18 Efficient Programming Tips

>>>a=3

>>>b=6

In this case, if you want to swap variables in C++, you definitely need an empty variable. But Python doesn’t need that, just one line, everyone pay attention:

Python Beginner Tutorial: 18 Efficient Programming Tips

>>>a,b=b,a

>>>print(a)>>>6

>>>print(b)>>>5

02 Dictionary Comprehensions and Set Comprehensions

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

Python Beginner Tutorial: 18 Efficient Programming Tips

>>> 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:

Python Beginner Tutorial: 18 Efficient Programming Tips

>>> # 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 dictionary where the keys are unique integers from 1 to 10, and the values are booleans indicating whether the key is even.

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

Python Beginner Tutorial: 18 Efficient Programming Tips

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

>>> my_set

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

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

03 Use Counter Objects for Counting

This may seem obvious, but it’s often forgotten. For most programmers, counting something is a common task and is not very challenging in most cases – here are a few ways to accomplish this task more simply.

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

Python Beginner Tutorial: 18 Efficient Programming Tips

>>> 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 data serialization format, widely used in various APIs and web services today. Using Python’s built-in JSON handling can make JSON strings somewhat readable, but when dealing with large data, it appears as a long, continuous line, making it difficult for the human eye to read.

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

Python Beginner Tutorial: 18 Efficient Programming Tips

>>> 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 any printed output look nicer.

05 Solve FizzBuzz

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

Write a program that prints numbers from 1 to 100, replacing multiples of 3 with “Fizz”, multiples of 5 with “Buzz”, and numbers that are multiples of both 3 and 5 with “FizzBuzz”.

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

Python Beginner Tutorial: 18 Efficient Programming Tips

for x in range(1,101):

print(“fizz”[x%3*len(“fizz”)::]+”buzz”[x%5*len(“buzz”)::] or x)

06 Inline if Statements

Python Beginner Tutorial: 18 Efficient Programming Tips

print(“Hello” if True else “World”)

>>> Hello

07 Concatenation

The last way mentioned is quite cool when binding two different types of objects.

Python Beginner Tutorial: 18 Efficient Programming Tips

nfc = [“Packers”, “49ers”]

afc = [“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 Comparisons

This is a convenient method that I have rarely seen in many languages.

Python Beginner Tutorial: 18 Efficient Programming Tips

x = 2

if 3 > x > 1:

print(x)

>>> 2

if 1 < x > 0:

print(x)

>>> 2

09 Iterate Over Two Lists Simultaneously

Python Beginner Tutorial: 18 Efficient Programming Tips

nfc = [“Packers”, “49ers”]

afc = [“Ravens”, “Patriots”]

for teama, teamb in zip(nfc, afc):

print(teama + ” vs. ” + teamb)

>>> Packers vs. Ravens

>>> 49ers vs. Patriots

10 Iterating Lists with Indices

Python Beginner Tutorial: 18 Efficient Programming Tips

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 the even numbers:

Python Beginner Tutorial: 18 Efficient Programming Tips

numbers = [1,2,3,4,5,6]

even = []

for number in numbers:

if number%2 == 0:

even.append(number)

Turn it into this:

Python Beginner Tutorial: 18 Efficient Programming Tips

numbers = [1,2,3,4,5,6]

even = [number for number in numbers if number%2 == 0]

12 Dictionary Comprehensions

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

Python Beginner Tutorial: 18 Efficient Programming Tips

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

Python Beginner Tutorial: 18 Efficient Programming Tips

items = [0]*3

print(items)

>>> [0,0,0]

14 Converting a List to a String

Python Beginner Tutorial: 18 Efficient Programming Tips

teams = [“Packers”, “49ers”, “Ravens”, “Patriots”]

print(“, “.join(teams))

>>> Packers, 49ers, Ravens, Patriots

15 Getting Elements from a Dictionary

Python Beginner Tutorial: 18 Efficient Programming Tips

I admit that try/except code is not elegant, but here is a simple way to try to find a key in a dictionary, if not found, the second parameter will set its variable value.

data = { ‘user’: 1, ‘name’: ‘Max’, ‘three’: 4}

try:

is_admin = data[‘admin’]

except KeyError:

is_admin = False

Replace it with this:

data = { ‘user’: 1, ‘name’: ‘Max’, ‘three’: 4}

is_admin = data.get(‘admin’, False)

16 Getting Subsets of a List

Python Beginner Tutorial: 18 Efficient Programming Tips

Sometimes, you only need part of the elements in 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]

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

Python Beginner Tutorial: 18 Efficient Programming Tips

from collections import Counter

print(Counter(“hello”))

>>> Counter({ ‘l’: 2, ‘h’: 1, ‘e’: 1, ‘o’: 1})

17 Itertools

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

Python Beginner Tutorial: 18 Efficient Programming Tips

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 an interesting fact; in Python, True and False are global variables, so:

Python Beginner Tutorial: 18 Efficient Programming Tips

False = True

if False:

print(“Hello”)

else:

print(“World”)

>>> Hello

We also prepared some Python learning materials for everyone.

Some screenshots:

Python Beginner Tutorial: 18 Efficient Programming Tips

Python automation operations for office

Python Beginner Tutorial: 18 Efficient Programming Tips

Python Beginner Tutorial: 18 Efficient Programming Tips

  1. How to get it:

  2. Those who need it can like and share to let more people see it. In the public account, just reply “python” to get it.

Leave a Comment