In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you what are the 18 Python efficient programming skills, the content is very detailed, interested friends can refer to, hope to be helpful to you.
When I first met the Python language, I felt that python met all the requirements of the programming language I had when I was a student. The efficient programming skills of the python language have made those of us who have been studying c or C++ for four years, excited and finally relieved. High-level language, if you can't do it like this, why talk about it?
01 swap variables
> axi3 > bread6
In this case, if you want to exchange variables in C++, you must need an empty variable. But python doesn't need it, just one line, you can see it clearly.
> print (a) > 6 > ptint (b) > 5
02 dictionary derivation (Dictionary comprehensions) and set derivation (Set comprehensions)
Most Python programmers know and have used list derivation (list comprehensions). If you are not familiar with the concept of list comprehensions-a list comprehension is a shorter, 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 collections 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 * example, we create a set with non-repeating elements based on some_list, and the set contains only even numbers. In the example of the dictionary table, we create an integer between 1 and 10 that key is not repeated, and value is Boolean to indicate whether key is even.
Another thing worth noting here is the literal representation of the set. We can simply create a collection in this way:
> my_set = {1,2,2,3,4} > my_set set ([1,2,3,4])
Instead of using the built-in function set ().
03 use Counter to count objects.
This sounds obvious, but it is often forgotten. Counting something is a common task for most programmers, and in most cases it's not very challenging-here are several ways to do it more easily.
Python's collections class library has a built-in subclass of the dict class that 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 beautifully print out JSON
JSON is a very good form of data serialization and is widely used by various API and web service today. Using python's built-in json processing, you can make the JSON string readable, but when it comes to large data, it is difficult for the naked eye to watch it as a long, continuous line.
In order to make the JSON data more friendly, we can use the indent parameter to output beautiful JSON. This is especially useful when interactively programming or logging in 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, you can also make anything else printout more beautiful.
05 resolve FizzBuzz
Some time ago, Jeff Atwood promoted a simple programming exercise called FizzBuzz. The following questions are cited:
Write a program that prints a multiple of 1 to 100 Fizz 3 to replace this number, a multiple of 5 prints "Buzz", and a number that is both a multiple of 3 and a multiple of 5 prints "FizzBuzz".
Here is a short, interesting way to solve this problem:
For x in range (1101): print "fizz" [x%3*len (fizz):] + "buzz" [x%5*len (buzz)::] or x
06 if statement is in the line
Print "Hello" if True else "World" > Hello
07 connection
The following * * method is very 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 such a great 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
11 list derivation
Given a list, we can swipe out the even list method:
Numbers = [1, for number in numbers, 2, 3, 4, 5, 6] even = [] for number in numbers: if number%2 = = 0: even.append (number)
Transformed into the following:
Numbers = [1, number for number in numbers if number%2 2, 3, 4, 5, 6] even = [number for number in numbers if number%2 = = 0]
12 dictionary derivation
Similar to list derivation, dictionaries can do the same thing:
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] * 3print items > [0je 0jue 0]
14 convert a list to a 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's an easy way to try to find key in the dictionary, and if you don't find the corresponding alue, set the second parameter to its variable value.
Data = {user: 1, name: Max, three: 4} try: is_admin = data [admin] except KeyError: is_admin = False
Replace it like 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 of the elements in the list. Here are some ways to get a subset of the list.
X = [1 print x [: 3] > # 3 print x [: 3] > [1 Magazine 2] # 4 print x in the middle # [1:5] > [2Lie3 print x [3:] > [4 pencils 5] # Odd item print x [:: 2] > [1Shing 3 Magne5] # even item print x [1 print 2] >
In addition to the built-in data types in python, the collection module also includes some special use cases, and Counter is very useful in some cases. If you have participated in Facebook HackerCup this year, you can even find its usefulness.
From collections import Counter print Counter ("hello") > Counter ({l: 2, h: 1, e: 1, o: 1})
17 iterative tool
Like the collections library, there is another library called itertools, which is really efficient for solving certain problems. One of the use cases is to find all the combinations, which can tell you all the impossible combinations of the 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 an interesting thing compared to practical techniques. In python, True and False are global variables, so:
False = True if False: print "Hello" else: print "World" > > Hello on the 18 Python efficient programming skills are shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.