1.重复元素判定
思路:数据结构中,集合具有数据不重复的属性,使用set()方法移除所有重复元素
def all_unique(list):
return len(list) == len(set(list))
eg:
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True
2.字符元素组成判定
思路:class collections.Counter
实现字典dict的一个子类,具有字典的__missing__
方法,所以当访问不存在的key 的时候,返回值为0
from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True
3.内存占用
思路:getsizeof()
返回对象的字节大小,单位“字节”
import sys
variable = 30
print(sys.getsizeof(variable)) # 24
4.字节占用
思路:string类型存在encode()方法,使用encoding='UTF-8’关键字参数,返回编码后的字符串
def byte_size(string):
return(len(string.encode('utf-8')))
byte_size('Hello World') # 11
5.打印N次字符串
思路:字符串拼接
n = 2
s = "Programming"
print(s*n) # PorgrammingProgramming
6.大写第一个字母
思路:使用字符串对象的title()方法,字符串中所有单词的首字母都转化为大写,请注意,非字母后的第一个字母将转换为大写字母
s = "programming is awesome"
print(s.title()) # Programming Is Awesome
7.分块
思路:通过list()方法将字典转换为列表时,会将字典的值社区,而仅仅将字典的键转换为列表
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))))))
chunk([1,2,3,4,5,6,7,8], 3) # [[1,2,3], [4,5,6], [7,8]]
8.压缩
思路:filter()方法第一个参数作为方法名称或者返回布尔值的对象,如果为true,则保留第二个参数列表中的值
def compact(lst):
return list(filter(bool, lst))
compact([0,1,False,2,'',3,'a','s',34]) # [1,2,3,'a','s',34]
9.解包
思路:调用zip()方法可以将打包好的成对列表解开成两组不同的元组
array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed) # [('a', 'c','e'),('b','d','f')]
10.链式对比
思路:在一行代码中使用不同的运算符对比多个不同的元素,逻辑与
a = 3
print(2<a<8) # True
print(1==a<2) # False
11.逗号连接
思路:将列表,字符串连接成单个字符串,并且每一个元素的分割方式可以通过调用join()方法的字符对象决定
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ",".join(hobbies))
# My hobbies are: basketball, football, swimming
12.元音统计
思路:通过正则表达式,给定列表提供匹配元素
import re
def count_vowels(str):
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
count_vowels('foobar') # 3
count_vowels('gym') # 0
13.首字母小写
思路:使用lower()方法将字符转换成小写,通过分片进行字符串拼接
def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
14.展开列表
思路:使用isinstance()
方法判断参数类型,用于决定将列表类型的参数arg中的元素依次添加到新的列表中,如果不是列表类型则直接作为元素添加到新的列表,列表的extend()将序列类型的参数添加到列表后面
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
deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]
15.列表的差
思路:set对象的方法difference()返回第一个列表的元素,且该元素不在第二个列表内
def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]
16.通过函数取差
思路:map()方法第一个参数为方法名称,依次用于第二个参数的列表内元素
def difference)by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
for math import floor
difference_by([2.1,1.2], [2.3,3.4], floor) # [1.2]
difference_by([{'x': 2}, {'x': 1}], [{'x': 1}], lambda v: v['x']) #[{'x': 2}]
17.链式函数调用
思路:在一行代码内调用多个参数
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
18.合并两个字典
思路:字典对象的update()方法将字典类型的参数中的键值对更新到调用方法的字典中;在python3.5或者更高的版本中,字典对象前的双星号****可将字典里的值取出,并用集合消除重复
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(merge_two_dics(a, b)) # {'y': 3, 'x': 1, 'z': 4}
def merge_dictionaries(a, b):
return {**a, **b}
a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}
19.将两个列表转化为字典
思路:zip()方法将两个列表打包(元素个数与最短的列表一致),返回元组列表,可以理解为降维,反之,单星号***表示解包,升维
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}
20.使用枚举
思路:枚举支持迭代的方式遍历成员,按照定义的顺序,如果有值重复的成员,只获取重复的第一个成员
list = ["a", "b", "c", "d"]
for index, element in enumerate(list):
print("Value", element, "Index", index)
# ('Value', 'a', 'Index', 0)
# ('Value', 'b', 'Index', 1)
# ('Value', 'c', 'Index', 2)
# ('Value', 'd', 'Index', 3)
21.执行时间
思路:time库中的time()方法可以返回当前时间的时间戳
import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) # 3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time) # ('Time: ', 1.1205673217773438e-05)
22.元素频率
思路:max()方法第一个参数为常见的可迭代的集合类型,第二个关键字参数可选,提供每次迭代用的方法名称
def most_frequent(list):
return max(set(list), key=list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list) # 2
23. 回文序列
思路:列表使用分片,第三个数字为负数可以从后向前取值,其绝对值表示步进值
def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
palindrome('taco cat') # True
24.不使用if-else的计算子
思路:operator模块提供计算的方法,通过字典类型的对象实现对计算方法的整合
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
25.Shuffle
思路:Fisher-Yates 算法用来将一个有限集合生成一个随机磐裂的算法(数组随机排序
,该算法生成的随机排列是等概率的
from copy import deepcopy
from randorm 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]
shuffle(foo) # [2,3,1]
26.交换值
思路:交换对象的引用的内存地址
def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
27.字典默认值
思路:字典的get方法遇到不存在的key,如果设置了默认值会返回默认值,并设置相应的字典项
a = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3
28. 二进制整数按字节反转
这里展示一种完全基于算术和位操作,不基于任何循环语句的思路
def reverseByte(byte):
return (byte * 0x0202020202 & 0x010884422010) % 1023
第二种思路:首先是2位2位为一组,交换前一半和后一半。再4位4位为一组,交换前一半和后一半。再8位为一组,交换前一半和后一半。举个例子,1 2 3 4 5 6 7 8反转
- 2个2个为一组,交换前一半和后一半, 变成: 2 1 4 3 6 5 8 7
- 4个4个为一组,交换前一半和后一半, 变成: 4 3 2 1 8 7 6 5
- 再8个为一组,交换前一半和后一半, 变成: 8 7 6 5 4 3 2 1