发布于 5年前

Python 不为人知但非常有用的小技巧

交换值

a,b = 5,10
print(a,b)

a,b = b,a
print(a,b)

输出

(5, 10)
(10, 5)

用列表中的所有元素创建单个字符串

a = ["Python","is","awesome"]
print(" ".join(a))

输出

Python is awesome

查询列表中出现频率最多的元素

a = [1,3,5,2,3,6,5,9,4,8,3]
print(max(set(a),key = a.count))

from collections import Counter

cnt = Counter(a)
print(cnt.most_common(3))

输出

3
[(3, 3), (5, 2), (1, 1)]

检查两个字符串是否相同

from collections import Counter

result = (Counter('abc') == Counter('abc'))
print(result)

result = (Counter('abm') == Counter('abc'))
print(result)

输出

True
False

反转字符串

a = 'abcdefg'
print(a[::-1])

for char in reversed(a):
    print(char)

num = 123456789
print(int(str(num)[::-1]))

输出

gfedcba
g
f
e
d
c
b
a
987654321

反转列表

a = [5,4,3,2,1]
print(a[::-1])

for ele in reversed(a):
    print(ele)

输出

[1, 2, 3, 4, 5]
1
2
3
4
5

转置二维数组

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

输出

[('a', 'c', 'e'), ('b', 'd', 'f')]

链式比较

b = 6
print(3 < b < 9)
print(1 == b < 10)

输出

True
False

链式函数调用

def product(a,b):
    return a * b

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

b = True
print((product if b else add)(5,6))

输出

30

列表复制

a = [1,2,3,4,5]
b = a
b[0] = 10
print(a)
print(b)

输出

[10, 2, 3, 4, 5]
[10, 2, 3, 4, 5]
a = [1,2,3,4,5]
b = a[:]
b[0] = 10
print(a)
print(b)

输出

[1, 2, 3, 4, 5]
[10, 2, 3, 4, 5]
a = [1,2,3,4,5]
print(list(a))

输出

[1, 2, 3, 4, 5]
a = [1,2,3,4,5]
print(a.copy())

输出

[1, 2, 3, 4, 5]
from copy import deepcopy

l = [[1,2],[3,4]]

l2 = deepcopy(l) 
print(l2)

输出

[[1, 2], [3, 4]]

字典值获取

"""当键不在字典中时,返回 空 或 默认值"""
d = {'a':1,'b':2}
print(d.get('c',3))

输出

3
©2020 edoou.com   京ICP备16001874号-3