提高Python效率的编程技巧

## 1. 交换值
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)

## 2. 字符串列表合并为一个字符串
sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)

## 3. 将字符串拆分为子字符串列表
sentence_string = "my name is George"
sentence_string.split()
print(sentence_string)

## 4. 通过数字填充初始化列表
[0]*1000 # List of 1000 zeros 
[8.2]*1000 # List of 1000 8.2's

## 5. 字典合并
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}

## 6.反转字符串
name = "George"
name[::-1]

## 7. 从函数返回多个值
def get_a_string():
  a = "George"
  b = "is"
  c = "cool"
  return a, b, c
sentence = get_a_string()
(a, b, c) = sentence

## 8. 列表解析式
a = [1, 2, 3]
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2

## 9. 遍历字典
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
for key, value in m.items():
  print('{0}: {1}'.format(key, value))
  
## 10. 同时遍历列表的索引和值
m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
  print('{0}: {1}'.format(index, value))
  
## 11. 初始化空容器
a_list = list()
a_dict = dict()
a_map = map()
a_set = set()

## 12. 删除字符串两端的无用字符
name = "  George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"

## 13. 列表中出现最多的元素
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

## 14. 检查对象的内存使用情况
import sys
x = 1
print(sys.getsizeof(x))

## 一行代码实现1--100之和
print(sum(range(101))) # sum(Iter)

## 在一个函数内部修改全局变量.利用global在函数声明 修改全局变量
g_var = 1
def func():
	global g_var
	g_var = 2

## 字典删除键和合并两个字典:del和update方法
dic = {
	"name": "mark lee",
	"age": 19
}
del dic['age']

dic.update({
	'name': 'jack ma'
})

## 使用set去除列表重复值
alist = [1,1,2,2,3,4]
new_list = [val for val in set(alist)]

## python2和python3的range(100)的区别
# - python2返回列表
# - python3返回迭代器,节约内存

## 生成随机整数、随机小数、0--1之间小数方法
random.randint(min, max) # 生成区间内的整数
np.random.randn(5) # 习惯用numpy库,利用np.random.randn(5)生成5个随机小数
random.random() # 0-1随机小数:random.random(),括号中不传参

## r 避免转义给字符串
print(r'\dad')# 结果 \dad 。这里的 r 表示需要原始字符串,不转义特殊字符

## 用lambda函数实现两个数相乘
_sum = lambda a,b: a*b
print(_sum(3,4))

## 用map实现数列平方
def s(a):
	return a**2

print(list(map(s, [2, 3, 4]))) # [4, 9, 16]

## filter方法求出列表所有奇数并构造新列表
def filter_func(x):
	return x % 2 == 1

alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = filter(filter_func, alist)
print([item for item in new_list]) # [1,3,5,7,9]

## reduce实现阶乘
from functools import reduce
print(reduce((lambda x, y: x * y), [1, 2, 3, 4, 5])) 
# ((((1 * 2) * 3) * 4) * 5)
## 字符串去重并排序
s = "baaddcfee"
_s = list(set(s)) # set去重之后再转为list类型
_s.sort(reverse=False)
# _s = _s.sort(reverse=False) # list是不 变数据类型,s.sort时候没有返回值.这么写是错的
new_s = "".join(_s)
print(new_s)  # abcdef

## 字典根据键从小到大排序
dic = {'name': 'mark', 'age': 21, 'sex': 0, 'height': 180}
sorted_dic = sorted(dic.items(), key=lambda x: x[0], reverse=False)
print(sorted_dic)

## 统计字符串每个单词出现的次数
s = "abbccccdeef"
print(Counter(s)['c']) # 4

## a=(1,)b=(1),c=("1") 分别是什么类型的数据?
print(type((1, ))) 	# 
print(type((1)))   	# 
print(type(('1')))	# 

## 两个列表合并
list1 = [1, 3, 5]
list2 = [2, 4, 6]
# extend可以将另一个集合中的元素逐一添加到列表中,区别于append整体添加.
# list1.append(list2) # [1, 3, 5, [2, 4, 6]]
list1.extend(list2) # 也可以 print(list1 + list2)
print(list1)

## 用datetime模块打印当前时间戳 “2020-03-21 20:40:03星期6”
_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + "星期" + str(datetime.datetime.now().isoweekday())
print(_time)

## (.*)和(.*?)匹配区别?
#(.*)是贪婪匹配,会把满足正则的尽可能多的往后匹配
#(.*?)是非贪婪匹配,会把满足正则的尽可能少匹配

## [[1,2],[3,4],[5,6]]一行代码展开该列表,得出[1,2,3,4,5,6]
alist = [[1, 2], [3, 4], [5, 6]]
print([i for a in alist for i in a])

## 字符和ASCII的相互转换
print(''.join([chr(ord(c) + 1) for c in 'abcde']))

## re.sub替换字符串中的数字
s = 'she is 22, but he is 30'
print(re.sub(r'\d+', "25", s, count=1))# she is 25, but he is 30

## a="hello"和b="你好"编码成bytes类型
a = b"hello"
print(a)
print("你好".encode())

b'hello'
b'\xe4\xbd\xa0\xe5\xa5\xbd'

## 保留两位小数
print(round(float(1.23456),2)) # 1.23

你可能感兴趣的:(Python)