程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

10 Python efficient programming tips!

編輯:Python

First time to know Python Language , Think python It meets all the requirements of programming language when you were in school .python The efficient programming skills of the language have made those who have been forced to learn for four years c perhaps c++ People who , You can't be excited , Finally free . High-level language , If you can't do this , What else are you talking about ?

01 Exchange variables

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

In this case, if you want to exchange variables in c++ in , You must need an empty variable . however python Unwanted , Just one line , You can see clearly

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

02 Dictionary derivation (Dictionary comprehensions) And set derivation (Set comprehensions)

Most of the Python Programmers know and use list derivation (list comprehensions). If you are right about list comprehensions The concept is not very familiar —— One list comprehension It's a shorter one 、 Simply create a list Methods .

>>> 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 rise , 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 use some_list Based on , Create a collection with non repeating elements , And the set contains only even numbers . And in the dictionary example , We created one key It's not repeated 1 To 10 Integer between ,value It's Boolean , Used to indicate key Is it an even number . Another notable thing 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 built-in functions set().

03 Use when counting Counter Count objects

It sounds obvious , But it's often forgotten . For most programmers , Counting one thing is a very common task , And in most cases it's not very challenging —— There are several ways to accomplish this task more easily .

Python Of collections There is a built-in dict Subclasses of classes , It's for 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 out JSON

JSON Is a very good form of data serialization , By today's various API and web service Use a lot of . Use python Built in json Handle , You can make JSON Strings have a certain readability , But when it comes to big data , It shows up as a very long 、 In a row , It's hard to see with the naked eye .

In order to make JSON The data are more friendly , We can use indent Parameter to output beautiful JSON. When programming interactively on the console or logging , This is especially useful :

>>> 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
    }
  ]
}

Again , Use the built-in pprint modular , Anything more beautiful can be printed out as well .

05 solve FizzBuzz

Some time ago Jeff Atwood Promoted a simple programming practice called FizzBuzz, The questions are quoted below :

Write a program , Print digit 1 To 100,3 Multiple printing “Fizz” To replace this number ,5 Multiple printing “Buzz”, For both 3 The multiple of 5 Multiple of the number printed “FizzBuzz”.

Here is a short one , An 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 way to bind two different types of objects looks like cool.

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 rarely seen in many languages

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

09 Iterate 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 Indexed list iterations

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved