python 技巧积累

Posted on Posted in python

python 技巧积累

变化变量值

a, b = b, a

将列表中的所有元素组合成字符串

a = ['a', 'b', 'c']                                                             
print(" ".join(a))

查找列表中频率最高的值

a = [1,2,3,4,5,6,2,2,2,6,3]                                                     
print(max(set(a), key = a.count))                                               
                                                                                
from collections import Counter                                                 
                                                                                
cnt = Counter(a)                                                                
print(cnt.most_common(3))

检查两个字符串是不是由相同字母不同顺序组成

from collections import Counter                                                 
                                                                                
str1 = 'acb'                                                                    
str2 = 'bac'                                                                    
                                                                                
Counter(str1) == Counter(str2)

反转字符串

a = 'abcdefghijklmn'                                                            
print(a[::-1])                                                                  
                                                                                
for char in reversed(a):                                                        
    print(char)                                                                 
                                                                                
num = 123456789                                                                 
print(int(str(num)[::-1]))

反转列表

a = [1,2,3,4,5]                                                                 
print(a[::-1])                                                                  
                                                                                
for ele in reversed(a):                                                         
    print(ele) 

转置二维数组

original = [['a','b'],['c','d'],['e','f']]                                      
transposed = zip(*original)                                                     
print(list(transposed))

=====>

[('a', 'c', 'e'), ('b', 'd', 'f')]

链式比较

b = 6                                                                           
print(4 < b < 7)                                                                
print(1 == b < 20)

链式函数调用

def product(a,b):                                                               
    return a*b                                                                  
                                                                                
def add(a,b):                                                                   
    return a+b                                                                  
                                                                                
b = True                                                                        
print((product if b else add)(5,7))

字典 get 方法

d = {'a':1, 'b':2}                                                              
print(d.get('c',3))

通过「键」排序字典元素

d = {'apple':18, 'orange':20, 'banana':5, 'rotten tomato':1}                    
print(sorted(d.items(), key = lambda x: x[1]))                                  
                                                                                
                                                                                
from operator import itemgetter                                                 
                                                                                
print(sorted(d.items(), key = itemgetter(1)))                                   
                                                                                
print(sorted(d, key=d.get)) 

For Else

a = [1,2,3,4,5]                                                                 
for el in a:                                                                    
    if el == 0:                                                                 
    ┆   break                                                                   
else:   # 迭代为空后执行                                                                        
    print('loop->')

转换列表为逗号分割符格式

items = ['foo', 'bar', 'xyz']                                                   
print(','.join(items))                                                          
                                                                                
numbers = [2,3,5,10]                                                            
print(','.join(map(str,numbers)))                                               
                                                                                
data = [2, 'hello', 3, 3.4]                                                     
print(','.join(map(str,data)))

合并字典

d1 = {'a':1}
d2 = {'b':2}

print({**d1, **d2})

print(dict( d1.items() | d2.items() ))

d1.update(d2)
print(d1)

列表中最小和最大值的索引

lst = [40, 10, 20, 30]                                                          
                                                                                
def minIndex(lst):                                                              
    return min(range(len(lst)), key=lst.__getitem__)                            
                                                                                
def maxIndex(lsg):                                                              
    return max(range(len(lst)), key=lst.__getitem__)                            
                                                                                
print(minIndex(lst))                                                            
print(maxIndex(lst))

移除列表中的重复元素

items = [2,2,3,3,1]                                                             
                                                                                
newitems2 = list(set(items))                                                    
print(newitems2)                                                                
                                                                                
from collections import OrderedDict                                             
                                                                                
items = ["foo", "bar", "bar", "foo"]                                            
                                                                                
print(list(OrderedDict.fromkeys(items).keys()))

存储列表元素到新的变量中

在解析列表时,变量的数目不应该超过列表中的元素个数

testList = [1,2,3]
a, b, c = testList
print(a,b,c)

打印引入模块的文件路径

import threading
import socket
print(threading)
print(socket)

检查 Python 中的对象

test= [1,3,5,7]
print(dir(test))

检查一个对象的内存使用

在 Python 2.7 中,一个 32 比特的整数占用 24 字节,在 Python 3.5 中利用 28 字节。为确定内存使用,我们可以调用 getsizeof 方法

x = 1
print(sys.getsizeof(x))
» 转载请注明来源:若我若鱼 » python 技巧积累

Leave a Reply

Your email address will not be published. Required fields are marked *

four + 11 =