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

8、Argpartition : Find N maximum values in an array

   np.argpartition(array, N)    对array中index为N的数字排序,比该数字大的放后面,反之放前面。

array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])index = np.argpartition(array, -5)[-5:]
index
array([ 6,  1, 10,  7,  0], dtype=int64)
np.sort(array[index]) array([
5, 6, 7, 9, 10])

9、Clip : How to keep values in an array within an interval

#Example-1
array = np.array([10, 7, 4, 3, 2, 2, 5, 9, 0, 4, 6, 0])
print (np.clip(array,2,6))[6 6 4 3 2 2 5 6 2 4 6 2]#Example-2
array = np.array([10, -1, 4, -3, 2, 2, 5, 9, 0, 4, 6, 0])
print (np.clip(array,2,5))[5 2 4 2 2 2 5 5 2 4 5 2]

10、Extract: To extract specific elements from an array based on condition

arr = np.arange(10)
arrarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])# Define the codition, here we take MOD 3 if zero
condition = np.mod(arr, 3)==0
conditionarray([ True, False, False,  True, False, False,  True, False, False,True])np.extract(condition, arr)
array([0, 3, 6, 9])

 11、setdiff1d : How to find unique values in an array compared to another

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
b = np.array([3,4,7,6,7,8,11,12,14])
c = np.setdiff1d(a,b)
carray([1, 2, 5, 9])

12、convert a list-like string to a list of lists

executable_output = '[0.011, 0.544, 2.314], [7.895, 6.477, 2.573]'
(1) list comprehension(居中)
(2)
literal_eval(最慢)
(3) json(最快)
具体参考https://stackoverflow.com/questions/43419856/python-fastest-and-most-efficent-way-to-convert-a-list-like-string-to-a-list-o?r=SearchResults


13、append,concatenate, vstack
list: append
array concatenate

14、for 与 filter,map, reduce
https://mp.weixin.qq.com/s/sdw-pp6ESbsevr_25dGh_Q
原文地址:https://www.cnblogs.com/573177885qq/p/11747783.html