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

使用 Python 总是可以轻松完成一些特定任务,这让人惊奇。一些比较繁琐的任务可以使用 Python 在单行代码中完成。下面是我收集的 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')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2. 二进制转十进制

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

3. 转换成小写字母

"Hi my name is Allwin".lower()
# 'hi my name is allwin' "Hi my name is Allwin".casefold()
# 'hi my name is allwin'
  • 1
  • 2
  • 3
  • 4
  • 5

4. 转换成大写字母

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

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

"convert string to bytes using encode method".encode()
# b'convert string to bytes using encode method'
  • 1
  • 2

6. 复制文件

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

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]])
  • 1

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
  • 1
  • 2
  • 3
  • 4
  • 5

9. 赋值交换

a,b = b,a
  • 1

10. 斐波那契数列

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

11. 将嵌套列表合并为一个列表

[item for sublist in main_list for item in sublist]
  • 1

12. 运行一个 HTTP 服务

python3 -m http.server 8000
  • 1

13. 反转列表

numbers[::-1]
  • 1

14. 求一个数的因数

import math; fact_5 = math.factorial(5)
  • 1

15. 使用“for”和“if”的列表解析

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]
  • 1
  • 2

16. 从列表中得到最长的字符串

words = ['This', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'
  • 1
  • 2
  • 3

17. 列表推导式

li = [num for num in range(0,100)]
# this will create a list of numbers from 0 to 99
  • 1
  • 2

18. 集合推导式

num_set = { num for num in range(0,100)}
# this will create a set of numbers from 0 to 99
  • 1
  • 2

19. 字典推导式

dict_numbers = {x:x*x for x in range(1,5) }
# {1: 1, 2: 4, 3: 9, 4: 16}
  • 1
  • 2

20. if-else

print("even") if 4%2==0 else print("odd")
  • 1

21. 无限循环

while 1:0
  • 1

22. 检查数据类型

isinstance(2, int)
isinstance("allwin", str)
isinstance([3,4,1997], list)
  • 1
  • 2
  • 3

23. While 循环

a=5
while a > 0: a = a - 1; print(a)
  • 1
  • 2

24. 使用“print()”写入文件

print("Hello, World!", file=open('file.txt', 'w'))
  • 1

25. 计算字符串中的某个字符出现的频率

print("umbrella".count('l'))# 2
  • 1

26. 合并两个列表

list1.extend(list2)# contents of list 2 will be added to the list1
  • 1

27. 合并两个字典

dict1.update(dict2)
# contents of dictionary 2 will be added to the dictionary 1
  • 1
  • 2

28. 合并两个集合

set1.update(set2)
# contents of set2 will be copied to the set1
  • 1
  • 2

29. 时间戳

import time; print(time.time())
  • 1

30. 出现次数最多的元素

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]
most_frequent_element = max(set(test_list), key=test_list.count)
# 4 However, this is not efficient and we can do the same using the collections module in a more efficient way like this. numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4] from collections import Counter
print(Counter(numbers).most_common()[0][0])# 4
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

31. 嵌套的列表推导式

numbers = [[num] for num in range(10)]
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
  • 1
  • 2

32. 八进制转十进制

print(int('30', 8))
# 24
  • 1
  • 2

33. 将键值对转换为字典

dict(name='allwin', age=23)
  • 1

34. 计算商和余数

quotient, remainder = divmod(4,5)
  • 1

35. 从列表中删除重复元素

list(set([4, 4, 5, 5, 6]))
  • 1

36. 对列表进行升序排序

First, let us sort the list using the sorted() method. The sorted method will **return the sorted list**.

sorted([5, 2, 9, 1])# [1, 2, 5, 9]

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]
li.sort() print(li)
# 1, 2, 5, 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

37. 对列表进行降序排序

sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]
  • 1

38. 获取一串小写字母

import string; print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
  • 1
  • 2

39. 获取一串大写字母

import string; print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • 1
  • 2

40. 获取字符串类型的0到9的数字

import string; print(string.digits)
# 0123456789
  • 1
  • 2

41. 十六进制转十进制

print(int('da9', 16))
# 3497
  • 1
  • 2

42. 人类可读的日期时间

import time; print(time.ctime())
# Thu Aug 13 20:16:23 2020
  • 1
  • 2

43. 将列表元素的字符串类型转换为整型

list(map(int, ['1', '2', '3']))
# [1, 2, 3]
  • 1
  • 2

44. 按"键"对字典进行排序

# d = {'five': 5, 'one': 1, 'four': 4, 'eight': 8}
{key:d[key] for key in sorted(d.keys())}
# {'eight': 8, 'five': 5, 'four': 4, 'one': 1}
  • 1
  • 2
  • 3

45. 按"值"对字典进行排序

# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
  • 1
  • 2
  • 3

46. 旋转列表

# li = [1,2,3,4,5]# right to left
li[n:] + li[:n] # n is the no of rotations
li[2:] + li[:2]
[3, 4, 5, 1, 2]# left to right
li[-n:] + li[:-n]
li[-1:] + li[:-1]
[5, 1, 2, 3, 4]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

47. 从字符串中删除数字

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))
# abcdeffgvcg
  • 1
  • 2

48. 转置矩阵

list(list(x) for x in zip(*old_list))
# old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]
  • 1
  • 2
  • 3

49. 从列表中过滤偶数

list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))
# [2, 4, 6]
  • 1
  • 2

50. 解包操作

a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
  • 1
  • 2
  • 3
  • 4

来自:https://blog.csdn.net/os373/article/details/121035063?spm=1000.2115.3001.5927#8_n__48

你应该知道的 50 个 Python 单行代码的更多相关文章

  1. Python小白需要知道的 20 个骚操作!

    Python小白需要知道的 20 个骚操作! Python 是一个解释型语言,可读性与易用性让它越来越热门.正如 Python 之禅中所述: 优美胜于丑陋,明了胜于晦涩. 在你的日常编码中,以下技巧可 ...

  2. 每个极客都应该知道的Linux技巧

    每个极客都应该知道的Linux技巧 2014/03/07 | 分类: IT技术 | 0 条评论 | 标签: LINUX 分享到:18 本文由 伯乐在线 - 欣仔 翻译自 TuxRadar Linux. ...

  3. 关于WPF你应该知道的2000件事

    原文 关于WPF你应该知道的2000件事 以下列出了迄今为止为WPF博客所知的2,000件事所创建的所有帖子. 帖子总数= 1,201 动画 #7 - 基于属性的动画 #686 - 使用动画制作图像脉 ...

  4. (0)开始 Raspberry Pi 项目前需要知道的 10 件事

    https://www.digikey.cn/zh/articles/techzone/2017/feb/10-things-to-know-before-starting-a-raspberry-p ...

  5. 理工科应该的知道的C/C++数学计算库(转)

    理工科应该的知道的C/C++数学计算库(转) 作为理工科学生,想必有限元分析.数值计算.三维建模.信号处理.性能分析.仿真分析...这些或多或少与我们常用的软件息息相关,假如有一天你只需要这些大型软件 ...

  6. 12个很少被人知道的CSS事实

    之前没有认真的研究过,padding-bottom的值如果是百分比,那么它的实际值是根据父类的宽度来调整的.我还以为是根据这个元素的本身的宽度来定义呢?汗..padding-top/padding-l ...

  7. PHP程序员应该知道的15个库

    最几年,PHP已经成为最受欢迎的一种有效服务器端编程语言.据2013年发布的一份调查报告显示,PHP语言已经被安装在全球超过2.4亿个网站以及210万台Web服务器之上.PHP代表超文本预处理器,它主 ...

  8. Android 程序员必须知道的 53 个知识点

    1. android 单实例运行方法 我们都知道 Android 平台没有任务管理器,而内部 App 维护者一个 Activity history stack 来实现窗口显示和销毁,对于常规从快捷方式 ...

  9. 嵌入式程序员应知道的0x10个C语言Tips

    [1].[代码] [C/C++]代码 跳至 [1] ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...

  10. 关于C#你应该知道的2000件事

    原文 关于C#你应该知道的2000件事 下面列出了迄今为止你应该了解的关于C#博客的2000件事的所有帖子. 帖子总数= 1,219 大会 #11 -检查IL使用程序Ildasm.exe d #179 ...

随机推荐

  1. 继承QAbstractTableModel QStyledItemDelegate实现自定义表格,添加进度条和选中框。

    由于项目要求,需要实现一个列表目录显示信息,并且需要实现每一项提供进度条和选项框功能,所以需要继承QAbstractTableModel和QStyledItemDelegate进行自定义. -自定义数 ...

  2. 真正“搞”懂HTTP协议10之缓存控制

    HTTP缓存相关的问题好像是前端面试中比较常见的问题了,上来就会问什么cache-control字段有哪些,有啥区别啥的.嗯--说实话,我觉得至少在本篇来说,HTTP缓存还算不上复杂,只是字段稍微多了 ...

  3. JAVA虚拟机17---栈帧(局部变量表-操作数栈-动态连接-返回地址)

    借鉴:转https://blog.csdn.net/u011069294/article/details/107106755,他的虚拟机专栏:https://blog.csdn.net/u011069 ...

  4. win10使用python自动化安装mysql8.0.11

    流程概要 下载mysql-8.0.11-winx64压缩包 解压 编辑配置文件my.ini 管理员权限cmd安装(注意初始化时设置默认密码为空) pymysql连接,执行sql操作. 代码实现 依赖: ...

  5. 利用ICSharpCode.SharpZipLib.dll解析 出错:“Wrong Local header signature: 0xFF8”

    分析原因 利用ICSharpCode.SharpZipLib.dll解析APK时,进入APK的AndroidXml获取时出现报错 出错代码 using (ICSharpCode.SharpZipLib ...

  6. soucrce insight4 使用

    1.快捷键 F8 高亮 ctrl + 左击 进入函数定义或变量声明处 Alt + , 后退 Alt + . 前进 ctrl + g 跳到固定行 shift + F3 选中一个单词按下后,可按F3,F4 ...

  7. adb简记

    ADB Android Debug Bridge(安卓调试桥) tools.它就是一个命令行窗口,用于通过电脑端与模拟器或者真实设备交互.在某些特殊的情况下进入不了系统,adb就派上用场啦! 前提条件 ...

  8. 跳板攻击之:reGeorg 代理转发

    跳板攻击之:reGeorg 代理转发 郑重声明: 本笔记编写目的只用于安全知识提升,并与更多人共享安全知识,切勿使用笔记中的技术进行违法活动,利用笔记中的技术造成的后果与作者本人无关.倡导维护网络安全 ...

  9. CCRD_TOC_2008年第3期

    中信国健临床通讯 2008年第3期 目 录   银屑病和银屑病关节炎 1.        国际皮肤病专家呼吁重视生物制剂治疗银屑病 原文: http://pharmatimes.com/forums/ ...

  10. map方法整理数据,接口返回值进行处理

    整理前: //map方法使thumb加上域名 --> var data =[ { id: "11", title: "新车小程序title1", thum ...