Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python小技巧 #50

Open
TokenYangForever opened this issue Sep 5, 2018 · 0 comments
Open

python小技巧 #50

TokenYangForever opened this issue Sep 5, 2018 · 0 comments

Comments

@TokenYangForever
Copy link
Owner

TokenYangForever commented Sep 5, 2018

交换变量的值

# pythonic的方式交换值
a,b = 1, 2
print(a, b)
a, b = b, a
print(b, a)

将一组list元素合并成一个字符串(js中join方法是存在于数组对象中,python是存在于字符串对象)

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

找出list中出现次数最多的元素

# max函数接收一个函数类型的命名参数key,比较过程中调用key函数,以key函数返回的结果进行比较
a = [1, 2, 3, 3, 4, 4, 5, 6, 3, 3, 2, 2 ]
print(max(set(a), key=a.count))

# 引入collections中的Counter
from collections import Counter
print(Counter(a).most_common()[0][0])

反转一个字符串

# 利用切片
a = 'abcd'
print(a[::-1])
# 通过reversed方法遍历
result = ''
for char in reversed(a):
    result += a
print(result)
# 数字类型的话,可以先转换成string,反转后再转换成Int
num = 123456789
print(int(str(num)[::-1]))

置换2d数组

# 比如将2d数组[[a,b], [c,d], [e,f]]变为 => [[a,c,e], [b,d,f]]
arr = [[a,b], [c,d], [e,f]]
print(list(zip(*arr)))

链式比较

# 用各种操作符进行链式比较
b = 6
print(4 < b < 7)
print(1 == b < 7)

链式调用函数

# 以相同的参数,根据不同条件,调用不同函数
import random
def funA (a, b) :
    return a * b

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

print((funA if random.random() < .5 else funB)(3, 4))

克隆一个list对象

a = [10, 2 ,3 ,4 ,5]
# 一种快速地浅克隆
b = a[:]

# 通过类型转换方法克隆
c = list(a)

# 直接用list的copy方法
d = a.copy()

# 引入deepcopy方法进行深度克隆
from copy import deepcopy
l = [[1,2], [3,4]]
l2 = deepcopy(l)

根据值排序字典对象

# 利用sorted函数,并传入key参数
d = {'a': 10, 'b': 5, 'c': 1}
sorted(d.items(), key=lambda x: x[1])

For Else

a = [1,2,3,4,5]
for el in a :
    if el == 0:
        break
else:
    print('没有从for循环中break的情况,会执行到这里的代码')

把list转换成逗号分隔的字符串

a = ['a', 'b', 'c']
','.join(a)
# 数组中包含非字符串的成员时,先转换类型
b = ['a', 1, 'c']
','.join(map(str, a))

合并字典对象

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

print({**d1, **d2})
print(dict(d1.items() | d2.items()))
# 将d2合并到d1
d1.update(d2)

获取一个list中最小/最大值的下标

lst = [40, 10, 20, 30]
min(range(len(lst)), key = lambda x: lst[x])
max(range(len(lst)), key = lambda x: lst[x])

去除字典中的重复项

items = [2, 2, 3, 3, 1]
print(list(set(items)))

解构函数参数

def myfunc(x, y, z):
    print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant