python snippets
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
相关推荐
xiaoseyihe 2020-11-16
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20