高效的单行python脚本

#-- coding: utf-8 - -

"""

Created on Wed Dec 6 13:42:00 2023

@author: czliu

"""

1. 平方列表推导

#使用列表推导法计算从 1 到 10 的数字平方

python 复制代码
squares = [x**2 for x in range(1, 11)]
print(squares)

2.求偶数

#可以使用列表推导式从列表中筛选偶数。还可以出于其他目的修改此代码。

python 复制代码
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)

3. 交换变量

#通常,交换变量的值需要另一个变量和一堆行,但在 Python 中,可以在一行中执行此操作。

python 复制代码
a=23
b=25
a, b = b, a
print(a,b)

4.反转字符串

#有时需要反转字符串。可以通过使用另一个变量和一个for循环来做到这一点,这有点复杂。可以用切片来代替

python 复制代码
reversed_string = "Hello, World!"[::-1]
print(reversed_string)

5. 计算字符串列表中的单词出现次数

#有一个句子列表,需要检查有多少个 X 单词。

python 复制代码
sentences = ["this"," world ","is","not"," that","world","all world is ","word"," in ","sentence!"]
for sentence in sentences:
	print(sentence)
word_count = sum(1 for sentence in sentences if "world" in sentence)
print(word_count)

6. 用于排序的 Lambda 函数

#可以使用 Lamba 函数根据特定键对字典列表进行排序。

python 复制代码
dict_list = {'a':28,'b':25,'c':76}
sorted_list = sorted(dict_list.items(), key=lambda x: x[1])
print(type(sorted_list))
print(sorted_list)

7. 在列表中查找唯一元素

#可以使用 set 从列表中获取唯一元素

python 复制代码
original_list = [12,34,12,45,'t','w','w']
unique_elements = list(set(original_list))

8. 检查回文

#回文是一个单词、短语或句子,其向后读法与向前读法相同。通过反转来检查字符串是否为回文。

python 复制代码
string = 'abcdcba'
is_palindrome = string == string[::-1]
print(is_palindrome)

9. 在 Sentece 中颠倒单词

#使用列表推导和功能颠倒句子中单词的顺序。join

python 复制代码
sentence = "this world is not that world,all world is word in sentence!"
reversed_sentence = ' '.join(sentence.split()[::-1])
print(reversed_sentence)

10. 检查字符串是否为回文(不区分大小写):

#检查字符串是否为回文,忽略大小写,通过反转它和函数。

python 复制代码
my_string = 'AbcdcBa'
is_palindrome = my_string.lower() == my_string[::-1].lower()
print(is_palindrome)
相关推荐
花酒锄作田4 小时前
FastAPI 使用 session 认证
python·fastapi
lsswear4 小时前
Python 并发 线程
开发语言·python
软件课代表CiCi4 小时前
运行库是什么?电脑缺运行库怎么办?c++运行库缺失修复全攻略
开发语言·c++·windows·电脑·dll修复·dll丢失·运行库
Ivanqhz5 小时前
MLIR OpBuilder
开发语言·python·mlir
梅孔立6 小时前
OpenCode + Windows PowerShell 完整安装使用教程
windows
2601_962364976 小时前
面向设备厂商:Windows Hello 认证摄像头核心要点
windows·安全·电脑
zxy28472253016 小时前
C# 音频倍速播放
c#·音频·naudio·soundtouch·倍速
威联通安全存储6 小时前
TS-h2287XU-RP 在家电制造总装与质检数据场景的部署
python·制造
泡泡鱼(敲代码中)7 小时前
Python 字符串 str 完整学习笔记
python·学习
troy1287 小时前
Python 基础语法(八):Web 后端开发、数据分析与可视化、网络爬虫、人工智能 / 大模型应用
前端·python·数据分析