文章目录
- 1、交互赋值
- 2 、拆分列表
- 3、使用 `in` 判断语句
- 4、使用 `join` 合并字符串
- 5、遍历列表及索引
- 6、推导式
- 7、循环嵌套
- 8、生成器替代列表
- 9、使用any/all函数
- 10、属性
- 11、使用 with 处理文件打开
- 12、使用 with 加锁
- 13、使用Counter统计次数
Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码。
1、交互赋值
a = 1
b = 2
temp = a
a = b
b = temp
a, b = b, a
2 、拆分列表
my_list = ['A', 'B', 'C']
simple0 = simple_list[0]
simple1 = simple_list[1]
simple2 = simple_list[2]
simpleA, simpleB, simpleC = my_list
3、使用 in
判断语句
if result == 'ok' or result == 1:
'''代码处理'''
if result in ['ok', 1]:
'''代码处理'''
4、使用 join
合并字符串
colors = ['red', 'yellow', 'blue', 'green']
result = ''
for i in colors:
result += i
colors = ['red', 'yellow', 'blue', 'green']
result = ''.join(colors)
5、遍历列表及索引
my_itmes = ['a', 'b', 'c', 'd', 'e']
i = 0
for item in my_itmes:
print(i, item)
i += 1
my_itmes = ['a', 'b', 'c', 'd', 'e']
for i, item in enumerate(my_itmes):
print(i, item)
6、推导式
old_list = ['A', 'B', 'C', 'D', 'E']
new_list = [item for item in old_list]
dict = {'key1': 'value1', 'key2': 'value2'}
d = {k: v for k, v in dict.items()}
simple_set = {x ** 2 for x in [1, -1, 2]}
7、循环嵌套
x_list = ['a', 'b', 'c', 'd']
y_list = ['A', 'B', 'C', 'D']
z_list = ['1', '2', '3', '4']
for x in x_list:
for y in y_list:
for z in z_list:
print(x, y, z)
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
print(x, y, z)
8、生成器替代列表
def calculate(n):
return n ** 2
def my_range(n):
i = 0
result = []
while i < n:
result.append(calculate(i))
i += 1
return result
def my_range(n):
i = 0
while i < n:
yield calculate(i)
i += 1
9、使用any/all函数
found = False
for item in my_list:
if condition(item):
found = True
break
if found:
'''代码操作'''
if any(condition(item) for item in my_list):
'''代码操作'''
10、属性
class Clock(object):
def __init__(self):
self.__hour = 1
def __setHour(self, hour):
self.__hour = hour
def __getHour(self):
return self.__hour
hour = property(__getHour, __setHour)
11、使用 with 处理文件打开
f = open('text.txt')
content = f.read()
f.close()
with open('text.txt') as f:
content = f.read()
12、使用 with 加锁
import threading
lock = threading.Lock()
lock.acquire()
try:
'''互斥操作'''
finally:
lock.release()
import threading
lock = threading.Lock()
with lock:
'''互斥操作'''
13、使用Counter统计次数
my_list = ['a', 'a', 'b', 'c', 'c', 'c']
def compute(my_list):
my_dict = {}
for key in my_list:
if key not in my_dict:
my_dict[key] = 1
else:
my_dict[key] = my_dict[key] + 1
return my_dict
from collections import Counter
def compute(my_list):
counter = Counter(my_list)
return dict(counter)