Python的17个骚操作,你都OK吗?

Python 是一门非常优美的语言,其简洁易用令人不得不感概人生苦短。在本文中,我将带大家回顾了17 个非常有用的 Python 技巧,例如查找、分割和合并列表等。这 17 个技巧都非常简单,但它们都很常用且能激发不一样的思路。

1.交换变量值

#交换变量值
a, b = 5, 10
print(a, b)
a, b = b, a
print(a, b)

 

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

a = ['Python ','is',' awesome']
b =''.join(a)
print(b)

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

'''most frequent element in a list'''
a = [1,2,3,1,2,3,2,2,4,5,1]
print(max(set(a),key = a.count))
'''using Counter from collections'''
from collections import Counter
cnt = Counter(a)
print(cnt.most_common(3))

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

from collections import Counter
str1 = "abcdef"
str2 = "afbecd"
print(Counter(str1) == Counter(str2))

5.反转字符串

'''reversinig string with special case of slice step param'''
a = 'abcdefghigklmnopqrstuvwxyz'
print(a[::-1])
'''itering over string contens in reverse efficiently'''
for char in reversed(a):
    print(char)
'''reversing an integer through type conversion and slicing'''
num = 123456789
print(int(str(num)[::-1]))

#反转列表
'''reversinig list with special case of slice step param'''
a = [5,4,3,2,1]
print(a[::-1])
'''itering over list contens in reverse efficiently'''
for ele in reversed(a):
    print(ele)

6.反转列表

'''reversinig list with special case of slice step param'''
a = [5,4,3,2,1]
print(a[::-1])
'''itering over list contens in reverse efficiently'''
for ele in reversed(a):
    print(ele)

7.转置二维数组

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

8.链式比较

b = 6
print(4 < b < 7)
print(1 == b <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.字典get方法

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

11.通过【键】排序字典元素

#通过【键】排序字典元素
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))

12.For Else

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

13.转换列表为逗号分隔格式

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

14.合并字典

d1 = {'a':1}
d2 = {'b':2}
print({**d1,**d2})

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

d1.update(d2)
print(d1)

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

lst = [40,10,20,30]
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))

16.移除列表中的重复元素

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

17..复制列表

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

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

a = [1,2,3,4,5]
b = a
b[0] = 10
print(a)
print(b)

a = [1,2,3,4,5]
b = a[:]
b[0] = 10
print(a)
print(b)

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

快快收藏起来吧,相信你在实践中一定会遇到这17个非常有用的功能!!!

你可能感兴趣的:(python)