1. 交换两个变量的值
a, b = 5, 10
print(a, b)
a, b = b, a
print(a, b)
2. 将列表中所有元素拼接成字符串
a = ["Python", "is", "Good"]
print(" ".join(a))
numbers = [2, 3, 5, 10]
print(",".join(map(str, numbers)))
data = [2, 'hello', 3, 3.14]
print(','.join(map(str, data)))
3. 查找列表中出现次数最多的值
a = [1, 2, 3, 1, 2, 3, 2, 2, 4, 5, 1]
print(max(set(a), key=a.count))
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))
# 2出现4 次 , 1 出现 3 次
# [(2, 4), (1, 3), (3, 2)]
4. 字符串反转
a = "abcdefghijklmnopqrstuvwxyz"
print(a[::-1])
for char in reversed(a):
print(char)
num = 123456789
print(int(str(num)[::-1]))
5. 反转列表
a = [5, 4, 3, 2, 1]
print(a[::-1])
for item in reversed(a):
print(item)
6. 转换二维数组
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*original)
print(list(transposed))
7. 链式函数调用
def multiplication(a, b):
return a * b
def add(a, b):
return a + b
b = False
print((multiplication if b else add)(5, 7))
8. 拷贝
a = [1, 2, 3, 4, 5]
b = a
b[0] = 10
print(a)
print(b)
a = [1, 2, 3, 4, 5]
b = a[:]
b[0] = 10
print(a)
print(b)
a = [1, 2, 3, 4, 5]
print(list(a))
print(a.copy())
from copy import deepcopy
d = [[1, 2], [3, 4]]
d2 = deepcopy(d)
print(d2)
9. 根据值进行字典排序
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}
print(sorted(d.items(), key=lambda x: x[1]))
from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))
print(sorted(d, key=d.get))
10. 合并字典
d1 = {'a': 1}
d2 = {'b': 2}
# python 3.5 才支持
print({**d1, **d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)
11. 获取列表中的最小值和最大值的索引
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))
print(maxIndex(lst))
# 最小值和最大值
print(min(lst))
print(max(lst))
12. 从列表中删除重复项
items = [2, 2, 3, 3, 1]
newitems = list(set(items))
print(newitems)
from collections import OrderedDict
items = ['foo', 'bar', 'bar', 'foo']
print(list(OrderedDict.fromkeys(items).keys()))
13. 将列表进行全排列组合
import itertools
horses = [1, 2, 3, 4]
print (list(itertools.permutations(horses)))
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]