10 Python efficient programming tips!

When you first know Python language, you feel that Python meets all the requirements for programming language when you go to school. The efficient programming skills of Python language make those who have been forced to learn c or c + + for four years excited and finally relieved. High level language, if you can't do this, what's high level?

01 exchange variables

>>>a=3

>>>b=6

In this case, if you want to exchange variables, you must need an empty variable in c + +. But python doesn't need it, just one line. You can see it clearly

>>>a,b=b,a

>>>print(a)>>>6

>>>ptint(b)>>>5

02 dictionary completions and set completions

Most Python programmers know and use list derivations. If you are not familiar with the concept of list completions - a list completions 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 dictionary tables:

>>> # 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_ Based on list, a set with non repeating elements is created, and the set contains only even numbers. In the example of dictionary table, we created a non repeated integer between 1 and 10, and value is Boolean to indicate whether the key is even. Another thing worth noting here is the literal representation of sets. We can simply create a collection in this way:

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

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

Instead of using the built-in function set().

03 Counter object used in counting

This sounds obvious, but it is often forgotten. Counting a thing is a common task for most programmers, and it's not very challenging in most cases - there are several ways to do this task more easily.

There is a subclass of the built-in dict class in Python's collections class library, which is dedicated to 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 beautiful print JSON

JSON is a very good form of data serialization, which is widely used by various API s and web service s today. Using python's built-in JSON processing can make the JSON string readable, but when large data is encountered, it appears as a long and continuous line, which is difficult for human eyes to watch.

In order to make JSON data more friendly, we can use the indent parameter to output beautiful JSON. This is especially useful when programming interactively or logging on 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
    }
  ]

}

Similarly, using the built-in pprint module can also make the printout of anything else more beautiful.

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 numbers from 1 to 100, print "Fizz" in multiples of 3 to replace this number, print "Buzz" in multiples of 5, and print "FizzBuzz" in multiples of both 3 and 5.

Here is a short and 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 connection

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

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 a simple method that I have never seen so great in many languages

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

09 iterating over 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 list iteration with index

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

Keywords: Python

Added by evildobbi on Mon, 10 Jan 2022 15:07:50 +0200