打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
你应该知道的 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)]
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
初学者应该了解的10个Python技巧
50条有趣的Python一行代码,建议收藏
快收藏!!整理了100个Python小技巧!!
Python最常用的基础语句分享!
CTF 绕过前端JS加密进行密码爆破
如何在一行代码中实现if-elif-else三分支语句
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服