高效的单行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)
相关推荐
ZZHow102416 小时前
02OpenCV基本操作
python·opencv·计算机视觉
计算机学长felix16 小时前
基于Django的“酒店推荐系统”设计与开发(源码+数据库+文档+PPT)
数据库·python·mysql·django·vue
站大爷IP16 小时前
Python随机数函数全解析:5个核心工具的实战指南
python
悟乙己16 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max50060016 小时前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频
AI原吾16 小时前
玩转物联网只需十行代码,可它为何悄悄停止维护
python·物联网·hbmqtt
云动雨颤17 小时前
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
python·单元测试
子兮曰17 小时前
🔥C盘告急!WSL磁盘暴增?三招秒清20GB+空间
前端·windows·docker
SunnyDays101117 小时前
Python 实现 HTML 转 Word 和 PDF
python·html转word·html转pdf·html转docx·html转doc
跟橙姐学代码18 小时前
Python异常处理:告别程序崩溃,让代码更优雅!
前端·python·ipython