Super dry! Share 40 tricks of Python language!

Keywords: Python

Welcome to focus on Python, data analysis, data mining and fun tools!

Hello, everyone, today I'd like to share 40 Python tips. If it's helpful to you, please give me a little praise. Pay attention to me. I won't get lost. Later, I'll write more practical skills, technical exchange and learning. You can get the way to join at the end of the article.

0. The two variable values are interchangeable

>>> a=1
>>> b=2
>>> a,b=b,a
>>> a
2
>>> b
1

1. Continuous assignment

a = b = c = 50

2. Automatic unpacking

>>> a,b,c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
>>>
>>>
>>> a, *others = [1,2,3,4]
>>> a
1
>>> others
[2, 3, 4]
>>>

4. Chain comparison

a = 15
if (10 < a < 20):
    print("Hi")

Equivalent to

a = 15
if (a>10 and a<20):
    print("Hi")

5. Duplicate list

>>> [5,2]*4
[5, 2, 5, 2, 5, 2, 5, 2]

6. Duplicate string

>>> "hello"*3
'hellohellohello'

7. Ternary operation

age = 30
slogon = "fucking great" if  age == 30 else "niubility"

Equivalent to

if age == 30:
    slogon = "fucking great"
else:
    slogon = "niubility"

8. Dictionary merge

>>> a= {"a":1}
>>> b= {"b":2}
>>> {**a, **b}
{'a': 1, 'b': 2}
>>>

9. String inversion

>>> s = "i love python"
>>> s[::-1]
'nohtyp evol i'
>>>

10. List to string

>>> s = ["i", "love", "pyton"]
>>> " ".join(s)
'i love pyton'
>>>

11. for else statement

Check whether the list foo has 0. If yes, the search will be ended in advance. If not, the "not found" will be printed“

found = False
for i in foo:
    if i == 0:
        found = True
        break
if not found: 
    print("Not found")

If you use the for else syntax to write, you can save a few lines of code

for i in foo:
    if i == 0:
        break
else:
    print("Not found")

11. Dictionary derivation

>>> m = {x: x**2 for x in range(5)}
>>> m
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>>

12. Use Counter to find the most elements in the list

>>> content = ["a", "b", "c", "a", "d", "c", "a"]
>>> from collections import Counter
>>> c = Counter(content)
>>> c.most_common(1)
[('a', 3)]
>>>

The first most element is a, which appears three times. You can also find the second or third most element in a similar way

13. Default value dictionary

Set the value in the dictionary as the list, which is the common method

>>> d = dict()
if 'a' not in d:
    d['a'] = []
d['a'].append(1)

Use the defaultdict default dictionary to build a dictionary whose initial value is an empty list

from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)

14. Assignment expression

This is a new feature of 3.8, and the assignment expression becomes the walrus operator: =, you can put the variable assignment and expression on one line. What does it mean? Just look at the code

>>> import re
>>> data = "hello123world"
>>> match = re.search("(\d+)", data)  # 3
>>> if match:                         # 4
...     num = match.group(1)
... else:
...     num = None
>>> num
'123'

Lines 3 and 4 can be combined into one line of code

>>> if match:=re.search("(\d+)", data):
...     num = match.group(1)
... else:
...     num = None
...
>>> num
'123'

15. Instance

The isinstance function can be used to judge the type of an instance. In fact, the second parameter can be a tuple composed of multiple data types. For example:

isinstance(x, (int, float))

# Equivalent to

isinstance(x, int) or isinstance(x, float)

Similar functions include startswitch and endswitch of strings, for example:

s.startswith(('"""', "'''"))

# Equivalent to

s.startswith("'''") or s.startswith('"""')

16. Share files with http.server

# python3
python3 -m http.server

# python2
python -m SimpleHTTPServer 8000

17. The zip function realizes the exchange of dictionary key value pairs

>>> lang = {"python":".py", "java":".java"}

>>> dict(zip(lang.values(), lang.keys()))
{'.java': 'java', '.py': 'python'}

18. Find the number that appears most frequently in the list

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4, 5]
>>> max(set(test), key=test.count)
4

19. Use slots to save memory

class MyClass(object):
    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()


print(sys.getsizeof(MyClass))


class MyClass(object):
    __slots__ = ['name', 'identifier']

    def __init__(self, name, identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()


print(sys.getsizeof(MyClass))

# In Python 3.5
# 1-> 1016
# 2-> 888

20. Extended list

>>> i = ['a','b','c']
>>> i.extend(['e','f','g'])
>>> i
['a', 'b', 'c', 'e', 'f', 'g']
>>>

21. List negative index

>>> a = [ 1, 2, 3]
>>> a[-1]
3

22. List slice

>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[3:6] # Elements between 3rd and 6th
[3, 4, 5]
>>> a[:5] # First 5 elements
[0, 1, 2, 3, 4]
>>> a[5:] # Last 5 elements
[5, 6, 7, 8, 9]
>>> a[::] # All elements (copy list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[::2] # Even term
[0, 2, 4, 6, 8]
>>> a[1::2] # Odd term
[1, 3, 5, 7, 9]
>>> a[::-1]  # Reverse list
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

23. Two dimensional array becomes one-dimensional array

import itertools
>>> a = [[1, 2], [3, 4], [5, 6]]
>>> i = itertools.chain(*a)
>>> list(i)
[1, 2, 3, 4, 5, 6]

24. Indexed iteration

>>> a = ['Merry', 'Christmas ', 'Day']
>>> for i, x in enumerate(a):
...     print '{}: {}'.format(i, x)
...
0: Merry
1: Christmas
2: Day

25. List derivation

>>> le = [x*2 for x in range(10)]
>>> le  # Multiply each number by two
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

>>> le = [x for x in range(10) if x%2 == 0]
>>> le  # Get even items
[0, 2, 4, 6, 8]

26. Generator expression

>>> ge = (x*2 for x in range(10))
>>> ge
<generator object <genexpr> at 0x01948A50>
>>> next(ge)
0
>>> next(ge)
2
>>> next(ge)
4
...
>>> next(ge)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

27. Set derivation

Python

>>> nums = {n**2 for n in range(10)}
>>> nums
{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

28. Judge whether the key exists in the dictionary

>>> d = {"1":"a"}
>>> d['2']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '2'
>>> '1' in d
True
>>> d['1']
'a'
>>> d.get("1")
'a'
>>> d.get("2")
>>>

29. Decorator

from functools import wraps

def tags(tag_name):
    def tags_decorator(func):
        @wraps(func)
        def func_wrapper(name):
            return "<{0}>{1}</{0}>".format(tag_name, func(name))
        return func_wrapper
    return tags_decorator

@tags("p")
def get_text(name):
    """returns some text"""
    return "Hello " + name

print(get_text("Python"))

>>><p>Hello Python</p>

30. Dictionary subset

>>> def sub_dicts(d, keys):
...     return {k:v for k, v in d.items() if k in keys}
...
>>> sub_dicts({1:"a", 2:"b", 3:"c"}, [1,2])
{1: 'a', 2: 'b'}

31. Reverse dictionary

>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>>
>>> zip(d.values(), d.keys())
<zip object at 0x019136E8>
>>> z = zip(d.values(), d.keys())
>>> dict(z)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

32. Named tuple

>>> from collections import namedtuple
>>> Point = namedtuple("Point", "x,y")
>>> p = Point(x=1, y=2)
>>> p.x
1
>>> p[0]
1
>>> p.y
2
>>> p[1]
2

33. Set dictionary default value

>>> d = dict()
>>> if 'a' not in d:
...     d['a'] = []
...
>>> d['a'].append(1)
>>> d
{'a': [1]}

>>> d.setdefault('b',[]).append(2)
>>> d
{'a': [1], 'b': [2]}
>>>

34. Ordered dictionary

>>> d = dict((str(x), x) for x in range(10))
>>> d.keys() # key disorder
dict_keys(['0', '1', '5', '9', '4', '6', '7', '8', '2', '3'])


>>> from collections import OrderedDict
>>> m = OrderedDict((str(x), x) for x in range(10))
>>> m.keys() # Keys are arranged in the order of insertion
odict_keys(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])

35. The maximum and minimum first n numbers in the list

>>> import heapq
a = [51, 95, 14, 65, 86, 35, 85, 32, 8, 98]
>>> heapq.nlargest(5,a)
[98, 95, 86, 85, 65]
>>> heapq.nsmallest(5,a)
[8, 14, 32, 35, 51]
>>>

36. Open the file

>>> with open('foo.txt', 'w') as f:
...     f.write("hello")
...

37. Combine the two lists into a dictionary

list_1 = ["One","Two","Three"]
list_2 = [1,2,3]
dictionary = dict(zip(list_1, list_2))
print(dictionary)

38. Remove duplicate elements from the list

my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
print(my_list)

39. Print calendar

import calendar

>>> print(calendar.month(2021, 1))
    January 2021
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

40. Anonymous function

def add(a, b):
    return a+b

Equivalent to

>>> add = lambda a,b:a+b
>>> add(1,2)
3

Technical exchange

Welcome to reprint, collect, gain, praise and support!

At present, a technical exchange group has been opened, with more than 2000 group friends. The best way to add notes is: source + Interest direction, which is convenient to find like-minded friends

  • Method ① send the following pictures to wechat, long press identification, and the background replies: add group;
  • Method ②: add micro signal: Python 666, remarks: from CSDN
  • WeChat search official account: Python learning and data mining, background reply: add group

Posted by flashman on Sat, 18 Sep 2021 20:10:39 -0700