wyqwilliam 2019-10-27
1、Find memory used by an object
import sys print(sys.getsizeof(5)) # 28 print(sys.getsizeof("Python")) # 55
2、Combine a list of strings into a single string
strings = [‘50‘, ‘python‘, ‘snippets‘] print(‘,‘.join(strings)) # 50,python,snippets
3、Find elements that exist in either of the two lists
def union(a,b): return list(set(a + b))union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) # [1,2,3,4,5,6,8]
4、Track frequency of elements in a list
from collections import Counter list = [1, 2, 3, 2, 4, 3, 2, 3] count = Counter(list) print(count) # {2: 3, 3: 3, 1: 1, 4: 1}
5、Find the most frequent element in a list
def most_frequent(list): # 原文取了set,不知道为什么也可以? return max(list, key = list.count)numbers = [1, 2, 3, 2, 4, 3, 1, 3] most_frequent(numbers) # 3
6、Use map functions
def multiply(n): return n * n list = (1, 2, 3) result = map(multiply, list) print(list(result)) # {1, 4, 9}
7、Use filter functions
arr = [1, 2, 3, 4, 5] arr = list(filter(lambda x : x%2 == 0, arr)) print (arr) # [2, 4]
参考 https://medium.com/better-programming/25-useful-python-snippets-to-help-in-your-day-to-day-work-d59c636ec1b