美文网首页
Python的骚操作,你值得拥有!

Python的骚操作,你值得拥有!

作者: 东风008 | 来源:发表于2020-05-07 22:10 被阅读0次

1 交换变量值

a, b = 5, 10
print(a,b)
a, b = b, a
print(a,b)

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

a = ['python','is','great']
print(' '.join(a))

3 查找列表中频率最高的值

a = [1,1,1,1,2,2,3,3,3,3]
print(max(set(a),key=a.count))

from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))

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

from collections import Counter
Counter(str1) == Counter(str2)

5 反转字符串

a = 'abcdefghijklmnopqrstuvwxyz'
print(a[::-1])

for i in reversed(a):
    print(i)

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

6 反转列表

a = [5,4,3,2,1]
print(a[::-1])

for i in reversed(a):
    print(i)

7 转置二维数组

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

8 链式比较

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

9 链式函数调用

def product(a,b):
    return a * b

def add(a,b):
    return  a + b

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

10 复制列表

b = a
b[0] = 10

b = a[:]
b[0] = 10

a = [1,2,3,4,5]
print(list(a))

a = [1,2,3,4,5]
print(a.copy())

from copy import deepcopy
l = [[1,2],[3,4]]
l2 = deepcopy(l)
print(l2)

11 字典 get 方法

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

12 通过「键」排序字典元素

d = {'apple':10,'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))

13 For Else

a = [1,2,3,4,5]
for i in a:
    if i == 0:
        break
    else:
        print('did not break out of for loop')

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

items = ['foo','bar','xyz']
print(','.join(items))

numbers = [2,3,5,20]
print(','.join(map(str,numbers)))

data = [2,'hello',3,3.4]
print(','.join(map(str,data)))

15 合并字典

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

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

d1.update(d2)
print(d1)

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

list = [40,15,20,45]
def minIndex(list):
    return min(range(len(list)), key=list.__getitem__)

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

print(minIndex(list))
print(maxIndex(list))

17 移除列表中的重复元素

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()))

相关文章

网友评论

      本文标题:Python的骚操作,你值得拥有!

      本文链接:https://www.haomeiwen.com/subject/zqzzghtx.html