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]

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

相关推荐
AI蜗牛之家2 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk2 小时前
python打卡第48天
开发语言·python
Eiceblue5 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550405 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂5 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP6 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@6 小时前
Python数据分析7
开发语言·python
老胖闲聊7 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点7 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI7 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python