Home  >  Article  >  Backend Development  >  Share 18 Python efficient programming tips

Share 18 Python efficient programming tips

WBOY
WBOYforward
2023-04-16 15:25:031072browse

Share 18 Python efficient programming tips

This article is compiled by Python Programming Time

The efficient programming skills of Python language make those of us who have studied c or c for four years in college extremely excited. It didn’t work, and I was finally free. High-level language, if it can't do this, why is it so advanced?

01 Exchange variables

>>>a=3
>>>b=6

In this case, if you want to exchange variables in c, you definitely need an empty variable. But python doesn’t need it, it only needs one line, everyone can see clearly

>>>a,b=b,a
>>>print(a)
>>>6
>>>ptint(b)
>>>5

02 Dictionary comprehensions and Set comprehensions

Most Python programmers know and use Through list comprehensions. If you're not familiar with the concept of list comprehensions - a list comprehension is a shorter, more concise way of creating 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 dictionary lists:

>>> # 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 use some_list as the basis and create a list with different A collection of repeating elements that contains only even numbers. In the example of the dictionary table, we created a key that is a non-repeating integer between 1 and 10, and the value is a Boolean type that indicates whether the key is an even number.

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

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

without using the built-in function set().

03 Use Counter to count objects when counting

This sounds obvious, but it is often forgotten. Counting something is a common task for most programmers, and in most cases not very challenging - here are a few ways to make it easier.

Python’s collections class library has a built-in subclass of the dict class, which is specially designed to do this kind of thing:

>>> 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 Beautifully print out JSON

JSON is a very good form of data serialization and is widely used by various APIs and web services today. Using Python's built-in json processing can make the JSON string readable to a certain extent, but when encountering large data, it appears as a long, continuous line, which is difficult for the human eye to view.

In order to make JSON data more friendly, we can use the indent parameter to output beautiful JSON. This is especially useful when programming or logging interactively at the console:

>>> import json
>>> print(json.dumps(data))# No indention
{"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 indention
{
"status": "OK",
"count": 2,
"results": [
{
"age": 27,
"name": "Oz",
"lactose_intolerant": true
},
{
"age": 29,
"name": "Joe",
"lactose_intolerant": false
}
]
}

Likewise, using the built-in pprint module can make anything else print more beautifully.

05 Solve FizzBuzz

Some time ago Jeff Atwood promoted a simple programming exercise called FizzBuzz. The question is quoted as follows:

Write a program to print the numbers 1 to 100, 3 Print "Fizz" to replace the number, "Buzz" for multiples of 5, and "FizzBuzz" for numbers that are both multiples of 3 and 5.

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 if statement in line

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

07 Connect

The last one below This method is very cool when binding two objects of different types.

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 Numerical comparison

This is such a great and simple method that I have seen in many languages

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

09 Iterate two lists at the same time

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

10 Indexed list iteration

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

11 List comprehension

Given a list, we can brush out the even list method:

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

converts to the following :

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

12 Dictionary comprehension

Similar to list comprehension, dictionaries can do the same job:

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

13 Initialize the values ​​of the list

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

14 List Convert to string

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

15 Get elements from dictionary

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

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

Replace with this

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

16 Get a subset of the list

Sometimes, you only need some elements in the list, here are some methods to get a subset of the list.

x = [1,2,3,4,5,6]
#前3个
print x[:3]
>>> [1,2,3]
#中间4个
print x[1:5]
>>> [2,3,4,5]
#最后3个
print x[3:]
>>> [4,5,6]
#奇数项
print x[::2]
>>> [1,3,5]
#偶数项
print x[1::2]
>>> [2,4,6]

In addition to python's built-in data types, the collection module also includes some special use cases. Counter is very practical in some situations. If you participated in this year's Facebook HackerCup, you can even find its practicality.

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

17 Iteration tool

Like the collections library, there is also a library called itertools, which can solve certain problems efficiently. One use case is to find all combinations, which can tell you all the impossible 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

This is a more practical technique than Very interesting thing, in python, True and False are global variables, so:

False = True
if False:
 print "Hello"
else:
 print "World"
>>> Hello

The above is the detailed content of Share 18 Python efficient programming tips. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete