码迷,mamicode.com
首页 > 编程语言 > 详细

python snippets

时间:2019-10-27 16:39:49      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:AMM   sizeof   useful   res   ack   style   return   tps   ber   

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

 

python snippets

标签:AMM   sizeof   useful   res   ack   style   return   tps   ber   

原文地址:https://www.cnblogs.com/573177885qq/p/11747783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!