人生苦短,我用python
Python 是一门非常优美的语言,其简洁易用令人不得不感概人生苦短。在本文中,作者 带我们回顾了 17 个非常有用的 Python 技巧,例如查找、分割和合并列表等。这 17 个技巧都非常简单,但它们都很常用且能激发不一样的思路。
1. 交换变量值
a,b = 1,2
a,b = b,a
2. 将列表中的元素组合成字符串
a = ['python','java','php','node']
result = "-".join(a)
3. 查找列表中元素频率最高的元素
a = [1,2,3,4,3,3,3,7,8,9]
max = max(set(a),key = a.count)
max() 函数 : 取最大值 max(1,2,3,4,5,6) // 6
count() 函数:统计次数 str.count(sub) // sub 在str中的出现次数
进阶示例:
from collections import Counter
# most_common(n) 按照counter的计数,按照降序,返回前n项组成的list; n忽略时返回全部
max = Counter(a).most_common(3)
Counter() 函数: 统计每个元素出现的次数,降序排列,并显示个数
4. 检查两个字符串,是否由相同字母组成
from collections import Counter
Counter(str1) == Counter(str2)
5. 6. 反转字符串、列表
a = 'abcdefghigklmn'
b = a[ : : -1] # 从头到尾,每隔-1取值;从尾到头,依次取值
for char in reversed(a):
print(char)
切片:
str[2:6] # 截取2-5字符串
str[2:] # 截取2-末尾的字符串
str[-2:] # 截取最后两个字符
str[1: :2] # 从索引1开始,每隔一个取一个
7. 转置二维数组
original = [['a','b'],['c','d'],['e','f']]
trans = list(zip(*original))
8. 链式比较
b = 6
print(4<b<7)
print(1==b < 7)
9. 链式函数调用
def product(a,b):
return a*b
def add(a,b):
return a+b
x = True
print((product if x else add)(5,7))
# x = True , 35 x = False 12
10. 复制列表
a = [1,3,5,7]
# 方法1:赋值
b = a
# 方法2:切片
b = a[:]
# list
b = list(a)
# copy
b = a.copy()
# 二维列表, deepcopy
from copy import deepcopy
list = [[1,2],[3,4]]
list_copy = deepcopy(list)
11. 字典get方法
x = {'a':1,'b':2}
print(x.get('c')) # 不存在返回None,存在则返回key对应的值
12. 通过[键]排序字典元素
# sorted 函数
d = { 'apple':10,'orange':20,'banana':5 }
print( sorted(d.items(),key:lambda x:x[1]) ) # 返回键-值,升序 [('banana',5),('apple',10),('orange',20)]
# itemgetter 类库
from operator import itemgetter
print(sorted(d.items(),key=itemgetter(1)))
# get 函数
print(sorted(d,key=d.get)) # 返回键,按照value升序 ['banana','apple','orange']
lambda 表达式还要加强啊,这种函数式编程思想是趋势
13. for else
a = [1,2,3,4,5]
for e in a:
if e == 0:
break
else
print('无参数0')
14. 转换列表为逗号分隔符 格式
# 字符串
items = ['a','b','c']
x = ','.join(items)
# 数字
numbers = [1,3,4,6,]
y = ','.join(map(str,numbers))
# 复合
data = [1,'hello',3,4]
z = '.'.join(map(str,data))
15. 合并字典
d1 = {'a':1}
d2 = {'b':2}
d_all_1 = {**d1,**d2}
d_all_2 = dict(d1.items() | d2.items())
d1.upgrate(d2) # 合并在d1中
16. 获取列表中最大和最小值的 索引
lst = [40,12,89,34]
def minIndex(lst):
return min(range(len(lst)),key=lst.__getitem__)
def maxIndex(lst):
return max(range(len(lst)),key=lst.__getitem__)
17. 移除列表中重复元素
# 使用 set 无重复属性
items = [2,2,3,3,4,5]
new_items = list(set(items))
# 使用 OrderdDict
from collections import OrderdDict
new_items = list( OrderedDict.fromkeys(items).keys())