1. 检查重复元素
def all_unique(lst):
return len(lst) == len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
print("1.检查重复元素")
print(all_unique(x))
print(all_unique(y))
print()
2. 变位词
检测两个字符串是否互为变位词
from collections import Counter
def anagram(first,second):
return Counter(first)==Counter(second)
print('2.变位词')
print(anagram('abc3','3bca'))
print()
3. 检查内存使用情况
import sys
variable = 30
str3 = '1'
print('3.检查内存使用情况')
print(sys.getsizeof(variable))
print(sys.getsizeof(str3))
print()
4. 字节大小计算
def byte_size(string):
return len(string.encode('utf-8'))
str4 = 'hello word'
print('4.字节大小计算')
print(byte_size(str4))
print()
5. 重复打印字符串N次
n = 2
s = 'Programming'
print('5.重复打印字符串N次')
print(s*n)
print()
6. 首字母大写
s = 'programming is awesome'
print('6.首字母大写')
print(s.title())
print()
7. 分块
以下方法使用range()将列表分块为指定大小的 较小列表
from math import ceil
def chunk(lst,size):
return list(
map(lambda x:lst[x*size:x*size+size],
list(range(0,int(ceil(len(lst)/size)))))
)
print('7. 分块')
print(chunk([1,2,3,4,5],2))
print()
8.压缩
以下方法使用fliter()
删除列表中的错误值(False,None,0,’’)
def compact(lst):
return list(filter(bool or '' or 0 ,lst))
lst8 = [0,1,False,2,'',' ',3,'a','s',34,True]
print('8.压缩')
print(compact(lst8))
print()
9.间隔数
以下代码段可以用来转换一个二维数组
arr9 = [['a','b'],['c','d'],['e','f']]
transposed = zip(*arr9)
print('9.间隔数')
print([i for i in transposed])
print()
10.链式比较
a = 3
print('10.链式比较')
print(2 < a < 8)
print(1 == a < 2)
print()
11.逗号分隔
以下代码段可将 字符串列表转换为单个字符串,用逗号分隔
hobbies = ['basketball','football','swimming']
print('11.逗号分隔')
print('My hobbies are: '+','.join(hobbies))
print()
12.计算元音字母数
以下方法可计算字符串中元音字母('a','e','i','o','u')
的数目
import re
def count_vowels(str_):
return len(re.findall(r'[aeiou]',str_,re.IGNORECASE))
print("12.计算元音字母数")
print(count_vowels('foobar'))
print(count_vowels('gym'))
print()
13.首字母恢复小写
def decapital(str_):
return str_[:1].lower()+str_[1:]
print("13.首字母恢复小写")
print(decapital('FooBar'))
print()
14.平面化
def spread(arg):
ret = []
for i in arg:
if isinstance(i,list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result =[]
result.extend(
spread(
list(
map(lambda x:deep_flatten(x) if type(x)==list else x,lst)
)
)
)
return result
print('14.平面化')
print(deep_flatten([1,[2],[[3],4],5]))
15.差异
只保留第一个迭代器中的值,从而发现两个迭代器之间的差异
def difference(a,b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
print("15.差异")
print(difference([1,2,3],[1,2,4]))
print()
16.寻找差异
下面的方法在将给定的函数应用于两个列表的每个元素后,返回两个列表之间的差值
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("16.寻找差异")
print(difference_by([2.1, 1.2], [2.3, 3.4],floor))
print(difference_by([{'x':2}, {'x':1}], [{'x':1}],lambda v:v['x']))
print()
17.链式函数调用
def add(a,b):
return a+b
def subtract(a,b):
return a-b
# a,b=4,5
a,b=5,4
print("17.链式函数")
print((subtract if a>b else add)(a,b))
print()
18.检查重复值
def has_duplicates(lst):
return len(lst)!=len(set(lst))
x = [1,1,2,2,3,4,5]
y = [1,2,3,4,5]
print('18.检查重复值')
print(has_duplicates(x))
print(has_duplicates(y))
print()
19.合并两个词典
def merge_two_dicts(a,b):
c = a.copy()
c.update(b)
return c
a = {'x':1,'y':2}
b = {'y':3,'z':4}
print("19.合并两个词典")
print(merge_two_dicts(a,b))
# 在python3.5及更高版本中,还可以执行
def merge_dictionaries(a,b):
return {**a,**b}
print("在python3.5及更高版本中,还可以执行")
print(merge_dictionaries(a,b))
print()
20.将两个列表转换成一个词典
def to_dictionary(keys,values):
return dict(zip(keys,values))
keys = ['a','b','c']
values = [2,3,4]
print('20.将两个列表转换成一个词典')
print(to_dictionary(keys,values))
print()
21.使用枚举
lst21 = ['a','b','c','d']
print("21.使用枚举")
for index,element in enumerate(lst21):
print("Value",element,"Index",index)
print()
22.计算所需时间
import time
# time() 或 clock()
# time.perf_counter or time.process_time
print("22.计算所需时间")
start_time = time.perf_counter()
a = 1
b = 2
c = a+b
print(c)
end_time = time.perf_counter()
total_time = end_time-start_time
print("Time:",total_time)
print()
23.try else指令
如果没有异常,则执行else里面的语句
print("23.try else指令")
try:
2*3
except TypeError:
print("An exception was raised")
else:
print("no exceptions")
print()
24.查找最常见元素
def most_frequent(lst):
return max(set(lst),key=lst.count)
lst24 = [1,2,1,21,21,1,1,14,2]
print('24.查找最常见元素')
print(most_frequent(lst24))
print()
25.判断回文
def palindrome(str_):
from re import sub
s = sub(r'\W+','',str_.lower())
return s == s[::-1]
print("25.判断回文")
print(palindrome('tacoc at'))
print()
26.没有if-else语句的简单计算器
import operator
action = {
"+":operator.add,
"-":operator.sub,
"/":operator.truediv,
"*":operator.mul,
"**":operator.pow
}
print("26.没有if-else语句的简单计算器")
print(action["-"](50,25))
print()
27.元素顺序打乱
通过 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("27.元素顺序打乱")
print(shuffle(foo))
print()
28.列表扁平化
def apread(arg):
ret = []
for i in arg:
if isinstance(i,list):
ret.extend(i)
else:
ret.append(i)
return ret
print("28.列表扁平化")
print(spread([1,2,3,[4,5,6],[7],8,9]))
print()
29.变量交换
def swap(a,b):
return b,a
a,b = -1,14
print("29.变量交换")
print(swap(a,b))
print()
30.获取缺失键的默认值
d = {'a':1,'b':2}
print('30.获取缺失键的默认值')
print(d.get('c',3))
print()