python代码提示太弱了_一些很实用的Python代码技巧

# most frequent element in a list

a = [1,2,3,1,2,3,2,2,2,4,5,1]

print(max(set(a), key = a.count))

# use Counter

from collections import Counter

cnt = Counter(a)

print(cnt.most_common(3))

# check two strings have same characters

from collections import Counter

str1 = "I see him"

str2 = "him I see"

print(Counter(str1) == Counter(str2))

# reverse string

b = 'abcdefghijklmnopqrstuvwxyz'

print(b[::-1])

for char in reversed(b):

print(char)

num = 123456789

print(int(str(num)[::-1]))

# transpose 2d array

original = [['a','b'], ['1','2'],['A','B']]

transposed = zip(*original)

print(list(transposed))

# call different functions with same arguments

def product(a,b):

return a*b

def add(a,b):

return a+b

x = True

print((product if x else add)(5,7))

# a shallow copy

e = [1,2,3,4,5]

d = e

d[0] = 10

print(d,e)

d2 = e[:]

d2[0] = 11

print(d2,e)

# deep copy

from copy import deepcopy

f = [[1,2],[3,4]]

f2 = deepcopy(f)

f[0] = ['x','y']

print(f,f2)

# sort a dict by its value with built-in sorted func

g = {'apple':50, 'banana':25, 'orange': 20, 'watermelon':10}

print(sorted(g.items(), key = lambda x:x[1]))

# use itemgetter instead of a lambda

from operator import itemgetter

print(sorted(g.items(), key=itemgetter(1)))

# sort dict by value

print(sorted(g, key = g.get))

# merge dict

d1 = {'x':1}

d2 = {'y':2}

print({**d1, **d2}) #python 3.5

print(dict(d1.items() | d2.items())) #python 3.5

d1.update(d2) #python 3.5

print(d1)

# convert list to comma separated string

data = [1,'re', 3, 'fa', 5]

print(','.join(map(str, data)))

# find index of min/max element

h = [40, 30, 20, 10, 50]

def minIndex(lst):

return min(range(len(lst)), key = lst.__getitem__)

def maxIndex(lst):

return max(range(len(lst)), key = lst.__getitem__)

print(minIndex(h))

print(maxIndex(h))

# remove duplicate items from list

i = [6,2,2,3,4,4,4,5]

print(list(set(i)))

from collections import OrderedDict

print(list(OrderedDict.fromkeys(i).keys()))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值