Python小技巧

字符串运算

>>> my_string = "Hello World!"
>>> print(my_string*2)
Hello World!Hello World!
>>> print(my_string[::-1])
!dlroW olleH
>>> word_list = ['awesome', 'is', 'this']
>>> print(' '.join(word_list[::-1]) + '!')
this is awesome!

列表推导式

>>> def func(x):
...     return x**2 + 5
...
>>> my_list = [1, 2, 3, 4, 5]
>>> print([func(x) for x in my_list if x%2 != 0])
[6, 14, 30]
>>> print([x**2 + 5 for x in my_list if x%2 != 0])
[6, 14, 30]

Lambda 和 Map

>>> func = (lambda x : x ** 2 + 5)
>>> print([func(1), func(3), func(5)])
[6, 14, 30]
>>> my_list = [2, 1, 0, -1, -2]
>>> print(sorted(my_list))
[-2, -1, 0, 1, 2]
>>> print(sorted(my_list, key = lambda x : x ** 2))
[0, 1, -1, 2, -2]
>>> print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6])))
[4, 10, 18]

单行条件语句

>>> x = 10
>>> print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
Horse
>>> x = 5
>>> print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
Duck
>>> x = -1
>>> print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
Baguette

zip()

>>> first_names = ["Peter", "Christian", "Klaus"]
>>> last_names = ["Jensen", "Smith", "Nistrup"]
>>> print([' '.join(x) for x in zip(first_names, last_names)])
['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']

交换变量值

a, b = b, a

查询列表中频率最高的值

>>> a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
>>> print(max(set(a), key = a.count))
2
>>> from collections import Counter
>>> cnt = Counter(a)
>>> print(cnt.most_common(3))
[(2, 4), (1, 3), (3, 2)]

检查两个字符串是不是由相同字母不同顺序组成

>>> str1 = "aabbccdd"
>>> str2 = "dcbaabcd"
>>> print(Counter(str1) == Counter(str2))
True

转置二维数组

>>> original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
>>> transposed = zip(*original)
>>> print(list(transposed))
[('a', 'c', 'e'), ('b', 'd', 'f')]

链式比较

>>> b = 6
>>> print(4 < b < 7)
True
>>> print(1 == b < 20)
False

链式函数调用

>>> def product(a, b):
...     return a * b
...
>>> def add(a, b):
...     return a + b
...
>>> b = True
>>> print((product if b else add)(5, 7))
35

复制列表

>>> a = [1, 2, 3, 4, 5]
>>> b = a[:]
>>> b
[1, 2, 3, 4, 5]
>>> b[0] = 10
>>> b
[10, 2, 3, 4, 5]
>>> a
[1, 2, 3, 4, 5]
>>> l = [[1, 2], [3, 4]]
>>> from copy import deepcopy
>>> l2 = deepcopy(l)
>>> print(l2)
[[1, 2], [3, 4]]

字典

dict.get(key, default=None)
get() 函数返回指定键的值,如果值不在字典中返回默认值。

>>> d = {'apple': 10, 'orange': 20, 'banana': 5, 'tomato': 1}
>>> print(sorted(d.items(), key=lambda x: x[1]))
[('tomato', 1), ('banana', 5), ('apple', 10), ('orange', 20)]
>>> print(sorted(d))
['apple', 'banana', 'orange', 'tomato']
>>> print(sorted(d.items(), key=lambda x: x[0]))
[('apple', 10), ('banana', 5), ('orange', 20), ('tomato', 1)]
>>> print(sorted(d, key=d.get))
['tomato', 'banana', 'apple', 'orange']

for else

# else get called when for loop does not reach break statement
a = [1, 2, 3, 4, 5]
for el in a:
	if el == 0:
		break
else:
	print("did not break out of for loop")

合并字典

>>> d1 = {'a' : 1}
>>> d2 = {'b' : 2}
>>> print({**d1, **d2})
{'a': 1, 'b': 2}
>>> print(dict(d1.items() | d2.items()))
{'b': 2, 'a': 1}
>>> d1.update(d2)
>>> print(d1)
{'a': 1, 'b': 2}

列表中最小和最大值的索引

>>> lst = [40, 10, 20, 30]
>>> def minIndex(lst):
...     return min(range(len(lst)), key=lst.__getitem__)
...
>>> def maxIndex(lst):
...     return max(range(len(lst)), key=lst.__getitem__)
...
>>> print(minIndex(lst))
1
>>> print(maxIndex(lst))
0

移除列表中的重复元素

>>> items = [2, 2, 3, 3, 1]
>>> newitems = list(set(items))
>>> newitems
[1, 2, 3]
>>> from collections import OrderedDict
>>> items = ['foo', 'bar', 'bar', 'foo']
>>> print(list(OrderedDict.fromkeys(items).keys()))
['foo', 'bar']

展开列表

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(lst):
    result = []
    result.extend(
        spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result


deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

Shuffle

from copy import deepcopy
from random import randint

def shuffle(lst):
    temp_lst = deepcopy(lst)
    m = len(temp_lst)
    while (m):
        m -= 1
        i = randint(0, m)
        temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
    return temp_lst


foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]

Switch-Case

import operator
action = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}
print(action['-'](50, 25)) # 25

Try else

try:
    2*3
except TypeError:
    print("An exception was raised")
else:
    print("Thank God, no exceptions were raised.")

#Thank God, no exceptions were raised.

执行时间

import time

start_time = time.time()

a = 1
b = 2
c = a + b
print(c) #3

end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)

# ('Time: ', 1.1205673217773438e-05)  

枚举索引和值

list = ["a", "b", "c", "d"]
for index, element in enumerate(list): 
    print("Value", element, "Index ", index, )

# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
#('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3)   

你可能感兴趣的:(Python)