网站首页 > 技术文章 正文
使用 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')
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)]
11. 将嵌套列表合并为一个列表
[item for sublist in main_list for item in sublist]
12. 运行一个 HTTP 服务
python3 -m http.server 8000
13. 反转列表
numbers[::-1]
14. 求一个数的因数
import math; fact_5 = math.factorial(5)
15. 使用“for”和“if”的列表解析
even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]
# [2, 4]
16. 从列表中得到最长的字符串
words = ['This', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'
17. 列表推导式
li = [num for num in range(0,100)]
# this will create a list of numbers from 0 to 99
18. 集合推导式
num_set = { num for num in range(0,100)}
# this will create a set of numbers from 0 to 99
19. 字典推导式
dict_numbers = {x:x*x for x in range(1,5) }
# {1: 1, 2: 4, 3: 9, 4: 16}
20. if-else
print("even") if 4%2==0 else print("odd")
21. 无限循环
while 1:0
22. 检查数据类型
isinstance(2, int)
isinstance("allwin", str)
isinstance([3,4,1997], list)
23. While 循环
a=5
while a > 0: a = a - 1; print(a)
24. 使用“print()”写入文件
print("Hello, World!", file=open('file.txt', 'w'))
25. 计算字符串中的某个字符出现的频率
print("umbrella".count('l'))# 2
26. 合并两个列表
list1.extend(list2)# contents of list 2 will be added to the list1
27. 合并两个字典
dict1.update(dict2)
# contents of dictionary 2 will be added to the dictionary 1
28. 合并两个集合
set1.update(set2)
# contents of set2 will be copied to the set1
29. 时间戳
import time; print(time.time())
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
31. 嵌套的列表推导式
numbers = [[num] for num in range(10)]
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
32. 八进制转十进制
print(int('30', 8))
# 24
33. 将键值对转换为字典
dict(name='allwin', age=23)
34. 计算商和余数
quotient, remainder = divmod(4,5)
35. 从列表中删除重复元素
list(set([4, 4, 5, 5, 6]))
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
37. 对列表进行降序排序
sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]
38. 获取一串小写字母
import string; print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
39. 获取一串大写字母
import string; print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
40. 获取字符串类型的0到9的数字
import string; print(string.digits)
# 0123456789
41. 十六进制转十进制
print(int('da9', 16))
# 3497
42. 人类可读的日期时间
import time; print(time.ctime())
# Thu Aug 13 20:16:23 2020
43. 将列表元素的字符串类型转换为整型
list(map(int, ['1', '2', '3']))
# [1, 2, 3]
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}
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}
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]
47. 从字符串中删除数字
''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))
# abcdeffgvcg
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]]
49. 从列表中过滤偶数
list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))
# [2, 4, 6]
50. 解包操作
a, *b, c = [1, 2, 3, 4, 5]
print(a) # 1
print(b) # [2, 3, 4]
print(c) # 5
翻译自:
https://allwin-raju-12.medium.com/50-python-one-liners-everyone-should-know-182ea7c8de9d
猜你喜欢
- 2025-05-11 5 个让代码更干净、更高效的 Python 好习惯
- 2025-05-11 掌握5 个 Python关键程序,编写更清晰、更高效的代码
- 2025-05-11 10个Python单行代码技巧,快速搞定数据清洗
- 2025-05-11 如何使用 Python 操作 Git 代码?GitPython 入门介绍
- 2025-05-11 一行代码可以做什么?Python给你答案
- 2025-05-11 应该要看的十条单行Python代码
- 2025-05-11 10 个 Python 单行代码搞定 Scikit-learn 任务,效率提升 80%!
- 2025-05-11 6行Python代码实现进度条效果(tqdm,Progress)
- 2025-05-11 Python进阶-day20: 代码风格与工具
- 2025-05-11 需要知道12 个 Python 单行代码1
- 05-27程序员用 Python 爬取抖音高颜值美女
- 05-27YOLO v3、FaceNet和SVM的人脸检测识别系统源码(python)分享
- 05-27「工具推荐」世界上最简单的人脸识别库 44.7 star
- 05-27开源人脸识别系统源码推荐
- 05-27Go 人脸识别教程
- 05-27Python 深度学习之人脸识别(yolo+facenet)
- 05-27简单的Py人脸识别
- 05-27Python编程 - 基于OpenCV实现人脸识别(实践篇)爬虫+人脸识别
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 82℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)