你应该知道的 50 个 Python 单行代码(一)

1. 字母移位词:猜字母的个数和频次是否相同

from collections import Counter s1 = 'below' s2 = 'elbow' print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')or we can also do this using the sorted() method like this.print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')

2. 二进制转十进制

decimal = int('1010', 2)  print(decimal) #10

3. 转换成小写字母

'Hi my name is Allwin'.lower() # 'hi my name is allwin' 'Hi my name is Allwin'.casefold() # 'hi my name is allwin'

4. 转换成大写字母

'hi my name is Allwin'.upper()  # 'HI MY NAME IS ALLWIN'

5. 字符串转换为字节类型

'convert string to bytes using encode method'.encode() # b'convert string to bytes using encode method'

6. 复制文件

import shutil; shutil.copyfile('source.txt', 'dest.txt')

7. 快速排序

qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])

8. n 个连续数之和

sum(range(0, n+1))This is not efficient and we can do the same using the below formula.sum_n = n*(n+1)//2

9. 赋值交换

a,b = b,a

10. 斐波那契数列

lambda x: x if x<=1 else fib(x-1) + fib(x-2)]
(0)

相关推荐