Here are some useful Python tips and tools I’ve collected over the years to help new Python learners.

1. Swap variables

x = 6
y = 5
x, y = y, x
print x
>>> 5
print y
>>> 6
Copy the code

2. If statement is in line

print "Hello" if True else "World"
>>> Hello
Copy the code

3. The connection

The last option below is 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
Copy the code

4. Number skills

# divide and round down
print 5.0//2
>>> 2
Two to the fifth
print 2支那5
>> 32
Copy the code

5. Note the division of floating point numbers

print 3./1.
>>> 2.9999999999999996
print 3.//1.
>>> 2.0
Copy the code

6. Numerical comparison

This is one of the few great simplicities I’ve seen in many languages

x = 2
if 3 > x > 1:
   print x
>>> 2
if 1 < x > 0:
   print x
>>> 2
Copy the code

7. Iterate over both lists simultaneously

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

>>> Packers vs. Ravens
>>> 49ers vs. Patriots
Copy the code

Python basic learning resources sharing, part-time exchange, technical exchange, are all friends who study hard together, welcome to join, little surprise.

8. Index list iteration

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

9. List derivations

Given a list, we can brush out even list methods:

numbers = [1.2.3.4.5.6]
even = []
for number in numbers:
    if number%2= =0:
        even.append(number)
Copy the code

Change to the following:

numbers = [1.2.3.4.5.6]
even = [number for number in numbers if number%2= =0]
Copy the code

Isn’t that awesome? Ha ha.

10. 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}
Copy the code

11. Initialize the list value

items = [0] *3
print items
>>> [0.0.0]
Copy the code

12. Lists are converted to strings

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

13. Get elements from the dictionary

I admit that the try/except code is not elegant, but a simple way is to try to look up the key in the dictionary, and if there is no corresponding alue set to its variable value with the second argument.

data = {'user': 1.'name': 'Max'.'three': 4}
try:
   is_admin = data['admin']
except KeyError:
   is_admin = False
data = {'user': 1.'name': 'Max'.'three': 4}
is_admin = data.get('admin'.False)
Copy the code

14. Get a subset of the list

Sometimes you only need a subset of the list. Here are some ways to get a subset of the list.

x = [1.2.3.4.5.6]
Before the # 3
print x[:3]
>>> [1.2.3]
# 4 in the middle
print x[1:5]
>>> [2.3.4.5]
# Last 3
print x[-3:]
>>> [4.5.6]
# odd term
print x[::2]
>>> [1.3.5]
Item # even
print x[1: :2]
>>> [2.4.6]
Copy the code

Collection of 15.

In addition to python’s built-in data types, the Collection module also includes special use cases where Counter is useful. If you attended the Facebook HackerCup this year, you might even find it useful.

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

16. Iteration tools

Like the Collections library, there is a library called IterTools that is really efficient for some problems. One use case is to find all combinations, which tells you all the ways elements in a group can’t be combined

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')
Copy the code

17.False == True

This is interesting compared to a practical technique. In Python, True and False are global variables, so:

False = True
if False:
   print "Hello"
else:
   print "World"
>>> Hello
Copy the code

That’s the end of this article, if you have any cool tricks, feel free to leave a comment below.