python用一行代码完成的26个日常任务

Python以其简洁优雅著称,能够用最少的代码行数实现强大的功能

1、计算列表平均值

python 复制代码
numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)

思路:使用sum()函数计算列表总和,len()函数获取长度,相除得到平均值。

2、 列表转字符串

python 复制代码
list1 = ['Hello', 'world']
str1 = ' '.join(list1)

思路:join()方法用于将列表中的元素连接成字符串,中间用指定字符(案例中用的空格)分隔。

3、 查找最大值

python 复制代码
n = [3, 1, 4, 1, 5, 9, 2, 6]
max_n = max(n)

思路:直接使用max()函数运算得到列表中的最大值。

4、 检查是否全是数字

python 复制代码
s = "12345"
is_all_digits = all(c.isdigit() for c in s)

思路:all()结合生成器表达式,检查序列中所有元素是否满足条件,这里检查每个字符是否为数字。

5、 反转字符串

python 复制代码
str1 = "hello"
str2 = str1[::-1]

思路:切片操作[::-1]用于反转字符串。

6、 平方一个列表的元素

python 复制代码
numbers = [1, 2, 3]
squared = [n**2 for n in numbers]

思路:列表推导式,对列表中的每个元素进行平方运算。

7、 判断是否为素数

python 复制代码
def is_prime(n):
    return all(n % i for i in range(2, int(n**0.5) + 1)) and n > 1

思路:使用all()和生成器表达式判断2到根号n之间是否有因子。

8、 字符串去重

python 复制代码
my_string = "hello"
unique_chars = ''.join(sorted(set(my_string)))
python 复制代码
思路:先用set()去重,再排序,最后用join()合并成字符串。

9、 计算字符串出现次数

python 复制代码
text = "hello world"
count = text.count('o')

思路:count()方法统计子字符串在原字符串中出现的次数。

10、 文件读取所有行

python 复制代码
with open('example.txt', 'r') as file:
    lines = file.readlines()

思路:使用上下文管理器安全读取文件,readlines()读取所有行到列表中。

11、 快速排序

python 复制代码
def quick_sort(lst):
    return sorted(lst)

思路: 使用内置的sorted()函数快速排序。

12、 生成斐波那契数列

python 复制代码
fibonacci = lambda n: [0, 1] + [fibonacci(i - 1)[-1] + fibonacci(i - 2)[-1] for i in range(2, n)]

思路:递归定义斐波那契数列。

13、 字典键值对交换

python 复制代码
dict1 = {'a': 1, 'b': 2}
dict2 = {v: k for k, v in dict1.items()}

思路:字典推导式,交换键值对。

14、 求两个集合的交集

python 复制代码
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection = set1 & set2

思路:使用集合的交集运算符&

15、 将字符串转换为整型列表

python 复制代码
s = "12345"
int_list = list(map(int, s))

思路:结合map()和list(),将字符串每个字符转换为整数并列表化。

16、 生成随机数

python 复制代码
import random
random_number = random.randint(1, 100)

思路:导入random模块,生成指定范围内的随机整数。

17、 混淆字符串的字母顺序

python 复制代码
from random import shuffle
s = "hello"
shuffled = ''.join(shuffle(list(s), random.random))

思路:将字符串转为列表,打乱顺序,再合并回字符串。

18、 将秒转换为时分秒

python 复制代码
seconds = 3661
hours, remainder = divmod(seconds, 3600)
minutes, seconds = divmod(remainder, 60)
time_format = f"{hours}:{minutes}:{seconds}"

思路:使用divmod()函数进行多次除法和取余操作,格式化输出时间。

19、 判断闰年

python 复制代码
year = 2020
is_leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

思路:根据闰年的规则,使用逻辑运算符组合判断条件。

20、 扁平化嵌套列表

python 复制代码
nested_list = [[1, 2], [3, 4, 5], [6]]
flattened = [item for sublist in nested_list for item in sublist]

思路:双层列表推导式,遍历每个子列表并展开其元素。

相关推荐
zone773910 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant10 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来11 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_11 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend12 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽12 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python