参考链接:https://zhuanlan.zhihu.com/p/83998758?utm_source=qq&utm_medium=social&utm_oi=728200852833075200
1.判断是否存在重复元素
def all_unique(a): return len(a)==len(set(a))
print(all_unique([1,1,2,3]))
输出:False
2.检查两个字符串的组成是否一样,即元素的种类和数目是否一致
def anagram(a,b): return Counter(a)==Counter(b) print(anagram("3abcda","acdba3")) 输出:True
3.内存占用
#32位系统 import sys variable = 38 print(sys.getsizeof(1)) print(sys.maxsize) 输出:14 2147483647
4.字节占用
def byte_size(string): return len(string.encode("utf-8")) print(byte_size("hello world")) 输出:11
5.打印N次字符串
print(“a”*3)
输出:aaa
6.大写第一个字母
print("abc".title())
输出:Abc
7.分块
from math import ceil def chunk(alist,size): return list(map(lambda x:alist[x*size:x*size+size], list(range(0,ceil(len(alist)/size))))) print(chunk([1,2,3,4,5],2)) 输出:[[1,2],[3,4],[5]]
8.压缩
使用python filter函数,其一般形式为filter(func,iterable)
例子1: def is_odd(a): return a%2==1 print(list(filter(is_odd,[1,2,3,4,5,6,7,8]))) 输出:[1,3,5,7] 例子2: print(list(filter(bool,[False,None,"",0,3,"a"]))) 输出:[3,"a"]
9.解包
a=[['a','b'],['c','d'],['e','f']] print(*a) 输出: ['a','b'] ['c','d'] ['e','f'] for i in zip(*a): print(i) 输出: ('a','c','e') ('b','d','f')
10.链式对比
a=3 print(2<a<4) 输出:True print(2==a<4) 输出:False
11.列表转字符串(用逗号相隔)
print(",".join(['a','b','c'])) 输出:a,b,c
12.元音统计(正则表达式的一种应用)
import re print(re.findall("[aeiou]","foobar")) 输出:3
13.展开列表
a=[1,[2],[[3],4],5] def spread(a): res=[] for i in a: if isinstance(i,list): res.extend(i) else: res.append(i) return res def deep_flatten(b): result=[] result.extend(spread((list(map(lambda x:deep_flatten(x) if type(x)==list else x,b))))) return result print(deep_flatten(a)) 输出:[1,2,3,4,5]
14.列表的差(返回第一个列表的元素,不再第二个列表中的)
def diff(a,b): set_a=set(a) set_b=set(b) comparison=set_a.difference(set_b) return list(comparison) print(diff([1,2,3],[1,2,4])) 输出:[3]
15.通过函数取差(如下方法会先应用一个给定的函数,然后再返回应用函数后结果有差别的列表的元素)
import math def difference_by(a,b,fn): b=set(map(math.floor,b)) return [item for item in a if math.floor(item) not in b] print(difference_by([1.2,2.1],[2.3,3.4],math.floor)) 输出:[1.2]
16.函数的链式调用(可以再一行代码内调用多个函数)
def add(a,b): return a+b def substract(a,b): return a-b a,b=4,5 print((substract if a>b else add)(a,b)) 输出:9
17.判断列表是否有重复值
print(len([1,2,2,3]==len(set([1,2,2,3]))) 输出:False
18.合并两个字典
def merge_two_dicts(a,b): c=a.copy() c.update(b) return c print(merge_two_dicts({1:2},{3:4})) 输出:{1:2,3:4} 再pyhton3.5及以上,直接print({**{1:2},**{3:4}})
19.把两个列表转换成字典
def to_dictionary(a,b): return dict(zip(a,b)) print(to_dictionary(["a","b"],[1,2])) 输出:{"a":1,"b":2}
20.使用枚举(能够同时取到index和value)
a=["a","b"] for index,val in enumerate(a): print(index,val) 输出: 0 a 1 b
21.执行时间(计算执行特定代码所用的时间)
import time start_time=time.time() for i in range(10000): print(i) end_time=time.time() total_time=end_time-start_time print(round(total_time,2)) 输出:0.17
22.Try else(可以多加一个else,如果没有触发错误,这个子句就会被执行)
try: 2*3 except TypeError: print("An exception") else: print("successful") 输出:successful
23.元素频率(统计出现次数最多的元素)
def most_frequent(a): return max(set(a),key=a.count) print(most_frequent([1,2,2,2,3,3])) 输出:2
24.回文序列(会先将所有字母转换成小写字母,并且移除非英文字母符号)
def palindrome(string): from re import sub s=sub("[W_]","",string.lower()) return s==s[::-1] print(palindrome("taco cat")) 输出:True
25.不使用if else计算子
import operator action={ "+":operator.add, "-":operator.sub, "*":operator.mul, "/":operator.truediv, "**":pow, } print(action["-"](50,25)) 输出:25
26.Shuffle(打乱列表排序的顺序)
from copy import deepcopy from random import randint def shuffle(a): tmp_list=deepcopy(a) n=len(tmp_list) while n: n-=1 i=randint(0,n) tmp_list[n],tmp_list[i]=tmp_list[i],tmp_list[n] return tmp_list print(shuffle([1,2,3])) 输出:[2,3,1](每次结果都不一样)