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]

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

相关推荐
985小水博一枚呀25 分钟前
【深度学习|可视化】如何以图形化的方式展示神经网络的结构、训练过程、模型的中间状态或模型决策的结果??
人工智能·python·深度学习·神经网络·机器学习·计算机视觉·cnn
CyreneSimon1 小时前
使用 LoRA 进行模型微调的步骤
python·transformer
ymchuangke1 小时前
数据清洗-缺失值处理-缺失值可视化图(竖线)
python·算法·数学建模
计算机学姐1 小时前
基于python+django+vue的旅游网站系统
开发语言·vue.js·python·mysql·django·旅游·web3.py
程序员小羊!2 小时前
Python语言基础教程(下)4.0
开发语言·python
huanxiangcoco2 小时前
73. 矩阵置零
python·leetcode·矩阵
一晌小贪欢2 小时前
Python基础知识——字典排序(不断补充)
python·json·python基础·字典·字典排序·python学习
YOLO数据集工作室2 小时前
Python介绍
开发语言·python
Hiweir ·3 小时前
机器翻译之创建Seq2Seq的编码器、解码器
人工智能·pytorch·python·rnn·深度学习·算法·lstm
不染_是非3 小时前
Django学习实战篇六(适合略有基础的新手小白学习)(从0开发项目)
后端·python·学习·django