1.合并字典
a = {'a':'1','b':'2','c':'3'}
b = {'a1':'3','b1':'4','c1':'5'}
#Python从版本3.5+起支持字典解压**。可以通过解压两个字典中的元素来创建新的“合并”字典
print(dict(a, **b))
#{'a': '1', 'b': '2', 'c': '3', 'a1': '3', 'b1': '4', 'c1': '5'}
print({**a, **b})
#{'a': '1', 'b': '2', 'c': '3', 'a1': '3', 'b1': '4', 'c1': '5'}
#Python 3.9引入了一种新的干净的(!)方法,使用联合运算符“|”合并字典。非常简洁。
print(a|b)
#{'a': '1', 'b': '2', 'c': '3', 'a1': '3', 'b1': '4', 'c1': '5'}
2.检查重复元素
def all_unique(lst): return len(lst) == len(set(lst)) #使用了 set() 属性,该属性将会从列表中删除重复的元素。 x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6] y = [1, 2, 3, 4, 5] print(all_unique(x)) # False print(all_unique(y)) # True print(len(x)) #10 print(len(set(x))) #6 print(len(y)) #5 print(len(set(y))) #5
3.最大小数
nums = [99, 111, 999] print(min(nums)) print(max(nums)) ''' 99 999 ''' nums = (99, 111, 999) print(min(nums)) print(max(nums)) ''' 99 999 '''
4.检查内存使用情况
import sys variable = '温酒斩华雄' print(sys.getsizeof(variable)) # 84
5.重复打印字符串n次
#重复打印字符串n次 n = 8; str ='python ' print(str*n) # python python python python python python python python
6.枚举
nums = ['99','111','999'] for i,v in enumerate(nums): print(i,v) ''' 0 99 1 111 2 999 ''' print(list(enumerate(nums))) ''' [(0, '99'), (1, '111'), (2, '999')] '''
7.ZIP
a = [1, 2, 3]
b = ['a', 'b', 'c']
print(tuple(zip(a,b)))
print(list(zip(a,b)))
print(dict(zip(a,b)))
'''
((1, 'a'), (2, 'b'), (3, 'c'))
[(1, 'a'), (2, 'b'), (3, 'c')]
{1: 'a', 2: 'b', 3: 'c'}
'''
array = [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(zip(*array)))
print(tuple(zip(*array)))
'''
[(1, 2, 3), ('a', 'b', 'c')]
((1, 2, 3), ('a', 'b', 'c'))
'''
8.反转数组
a = [1,3,5,7,9] print(a) b = a[::-1] print(b)
9.首字母大写
#使用 title() 方法将字符串内的每个词进行首字母大写 s = "programming is awesome" print(s.title()) # Programming Is Awesome
10.计算所需时间
#计算执行特定代码执行所需时间
import time
start_time = time.time()
sum = 0
for i in range(1000001):
sum += i
i+=1
print(sum)
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
'''
500000500000
Time: 0.11997008323669434
'''



