s = 'hello world'
print(s.title())
输出:
Hello World
将列表连接成单个字符串,且每个元素间分隔方式设为逗号
hobbies = ['basketball','football','baseball']
print('My hobbies are:'+','.join(hobbies))
输出:
My hobbies are:basketball,football,baseball
给定具体的大小,定义一个函数以这个大小切割列表
from math import ceil
def chunk(lst,size):
return list(map(lambda x: lst[x*size:x*size+size],list(range(0,ceil(len(lst)/size)))))
print(chunk([1,2,3,4,5],2))
输出:
[[1, 2], [3, 4], [5]]
def merge_dicts(a,b):
c = a.copy()
c.update(b)
return c
a = {'x':1,'y':2}
b = {'z':3}
print(merge_dicts(a,b))
# python3.5以上,合并字典
print({**a,**b})
输出:
{'x': 1, 'y': 2, 'z': 3}
{'x': 1, 'y': 2, 'z': 3}
检查给定的字符串是不是回文序列,首先把所有字母转化为小写,并移除非英文字母符号。最后,比较字符串与反字符串是否相等,相等则是回文序列
from re import sub
def palindrome(s):
s = sub('[\W_]','',s.lower())
return s == s[::-1]
print(palindrome('abcba'))
输出:
True
检查两列表是不是有重复项
def has_same(ls):
return len(ls) != len(set(ls))
x = [1,2,3,4,3]
y = [1,2,3]
print(has_same(x))
print(has_same(y))
输出:
True
False
将打包好的成对列表解开成两组不同的元组
array = [['a','b'],['c','d'],['e','f']]
transposed = zip(*array)
print(list(transposed))
输出:
[('a', 'c', 'e'), ('b', 'd', 'f')]
一行代码使用不同运算符对比多个不同元素
a = 3
print(2 < a < 8)
print(1 == a < 2)
输出:
True
False
一行代码调用多个函数
def add(a,b):
return a+b
def subtract(a,b):
return a-b
a,b = 4,5
c,d = 5,6
print((subtract if a>b else add)(a,b))
print((subtract if c>d else add)(c,d))
输出:
9
11
返回第一个列表的元素,其不在第二个列表内。如果同时返回第二个列表独有元素,还需加一句 set_b.difference(set_a)
def unique(a,b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
print(unique([1,2,3],[1,2,4]))
输出:
[3]
检查变量所占用内存
import sys
var = 25
print(sys.getsizeof(var))
输出:
28
除了使用for循环遍历,还可以使用枚举获取列表的值和索引
ls = ['a','b','c']
for index,value in enumerate(ls):
print('Value:',value,'Index:',index)
输出:
Value: a Index: 0
Value: b Index: 1
Value: c Index: 2
def decapital(string):
return string[:1].lower()+string[1:]
print(decapital('FooBar'))
输出:
fooBar
首先应用一个指定的函数,然后返回应用函数后结果有差别的列表元素
from math import floor
def difference_by(a,b,fn):
b = set(map(fn,b))
return [item for item in a if fn(item) not in b]
print(difference_by([2.1,1.2],[2.3,3.4,4.5],floor)) #取整只有1.2不同
print(difference_by([{'x':2},{'x':1}],[{'x':1}],lambda v:v['x']))
输出:
[1.2]
[{'x': 2}]
不使用条件语句,就实现加减乘除、求幂操作,它通过字典实现
import operator
action = {
"+":operator.add,
"-":operator.sub,
"*":operator.mul,
"/":operator.truediv,
"**":pow
}
print(action["-"](50,23))
输出:
27
将布尔型的值去掉,例如(False,None,0,‘’),使用filter()函数
def compact(lst):
return list(filter(bool,lst))
print(compact([0,1,False,2,'',3,'a','s',34]))
根据元素频率取列表中最常见的元素
def most_frequent(lis):
return max(set(list),key = list.count)
list = [1,2,13,2,1,1,3,4,2,2]
print(most_frequent(list))
输出:
2
用正则表达式,统计字符串中的元音(‘a’,‘e’,‘i’,‘o’,‘u’)的个数
import re
def count_yuan(str):
return len(re.findall(r'[aeiou]',str,re.IGNORECASE)) #re返回一个列表,忽略大小写搜索
print(count_yuan('fadoor'))
print(count_yuan('YAeood'))
输出:
3
4
通过递归的方式将列表的嵌套展开为单个列表
def flatten(li):
return sum(([x] if not isinstance(x,list) else flatten(x) for x in li),[])
print(flatten([1,[2],[[3,4],5]]))
输出:
[1, 2, 3, 4, 5]
检测列表是否存在重复元素
def all_unique(ls):
return len(ls) == len(set(ls))
x = [1,2,1,3,2,3,4,5]
y = [1,2,3,4]
print(all_unique(x))
print(all_unique(y))
输出:
False
True
通过key取对应的value值,可以通过以下方式设置默认值。如果get()方法没有设置默认值,如果遇到不存在的key,则返回None
d = {'a':1,'b':2}
print(d.get('a'))
print(d.get('c'))
输出:
1
None
检查两字符串元素是否相同
from collections import Counter
def anagram(first,second):
return Counter(first) == Counter(second)
print(anagram('abdc2','dab2c'))
输出:
True
检测字符串所占字节数
def byte_size(s):
return len(s.encode('utf-8'))
print(byte_size('Hello,world'))
print(byte_size(''))
输出:
11
4
n = 2
s = 'csdn'
print(s*n)
输出:
csdncsdn
这个算法会打乱列表,它主要通过Fisher-Yates算法对新列表排序
from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0,m)
temp_lst[m],temp_lst[i] = temp_lst[i],temp_lst[m]
return temp_lst
foo = [1,2,3]
print(shuffle(foo))
输出:
[3, 2, 1] #不是唯一值,是随机的
使用try/except语句的时候可以加一个else子句,如果没有触发错误,运行这个子句
try:
2*3
except TypeError:
print('An exception was raised')
else:
print('Thank god,no exception was raised')
输出:
Thank god,no exception was raised
计算执行特定代码所花费的时间
import time
start_time = time.time()
a = 1
b = 2
c = a * b
print(c)
end_time = time.time()
total_time = end_time - start_time
print('Time:',total_time)
输出:
2
Time: 0.0010042190551757812
def to_dicts(keys,values):
return dict(zip(keys,values))
keys = ['a','b','c']
values = [1,2,3]
print(to_dicts(keys,values))
输出:
{'a': 1, 'b': 2, 'c': 3}