关于python的17个骚操作

python的性能一直被人所嫌弃,但是真的很方便,可以忽略底层实现,拿来即用,很适合入门

这是我在机器之心上面看到的一篇文章,分享给大家
https://mp.weixin.qq.com/s/NfH2VvYzx_DrDfLUJ6O3-g

另外这个公众号也不错,微信,知乎平台上都有,要时刻关注行业动态哦~小心别掉队


  1. 交换变量值
a,b = 5,10
print(a,b)
a,b = b,a
print(a,b)
5 10
10 5
  1. 将列表中所有元素组合成字符串
a = ['python','is','awesome']
print(' '.join(a))
python is awesome
  1. 查找列表中频率最高的值
a = [1,2,3,1,1,5,8,1,1]
print(max(set(a),key=a.count))

from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))
1
[(1, 5), (2, 1), (3, 1)]
  1. 检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter
str1 = 'abc'
str2 = 'bca'
Counter(str1) == Counter(str2)
True
  1. 反转字符串
a = 'hello alicelmx'
print(a[::-1])

for char in reversed(a):
    print(char,end='')
    
num = 1234556789
# print('\n')
print(int(str(num)[::-1]))
xmlecila olleh
xmlecila olleh9876554321
  1. 反转列表
a = [5,4,3,2,1]

print(a[::-1])

for ele in reversed(a):
    print(ele,end='')
[1, 2, 3, 4, 5]
12345
  1. 转置二维数组
original = [['a','b'],['c','d']]
transposed = zip(*original)
print(list(transposed))
[('a', 'c'), ('b', 'd')]
  1. 链式比较
b = 6
print(4<b<7)
print(1==b<20)
True
False
  1. 链式函数调用
def product(a,b):
    return a*b
def add(a,b):
    return a+b

b = False
print((product if b else add)(5,7))

12
  1. 复制列表
b = a
b[0] = 10
print(b)

c = a.copy()
print(c)

from copy import deepcopy
l = [[1,2],[3,4]]
l2 = deepcopy(l)
print(l2)
[10, 4, 3, 2, 1]
[10, 4, 3, 2, 1]
[[1, 2], [3, 4]]
  1. 字典的get方法
d = {'a':1,'b':2}
print(d.get('a',1))
print(d)
1
{'a': 1, 'b': 2}
  1. 通过键排序字典元素
d = {'apple':1,'orange':3,'pear':0}
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))
[('pear', 0), ('apple', 1), ('orange', 3)]
[('pear', 0), ('apple', 1), ('orange', 3)]
['pear', 'apple', 'orange']
  1. for else
a = [1,2,3,4,5]

for el in a:
    if el == 0:
        break
else:
    print('!!!')
!!!
  1. 将列表转化为逗号分隔格式
items = ['foo','bar','xyz']
print(','.join(items))

nums = [2,3,4,5]
print(','.join(map(str,nums)))
foo,bar,xyz
2,3,4,5
  1. 合并字典
d1 ={'a':1}
d2 = {'b':2}

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

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

d1.update(d2)
print(d1)
{'a': 1, 'b': 2}
{'b': 2, 'a': 1}
{'a': 1, 'b': 2}
  1. 列表中最大和最小值的索引
lst = [40,100,1,3]

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

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

print(minIndex(lst))
print(maxIndex(lst))
2
1
  1. 移除列表中的重复元素
# 打乱原始顺序
items = [1,1,14,6,7,3]
newitems = list(set(items))
print(newitems)

# 保持原始顺序不变
from collections import OrderedDict
print(list(OrderedDict.fromkeys(items).keys()))
[1, 3, 6, 7, 14]
[1, 14, 6, 7, 3]

你可能感兴趣的:(python基础知识)