高效的单行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)
相关推荐
TF男孩2 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在7 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP9 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
mudtools9 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
用户83562907805114 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i15 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050615 小时前
【ESP32-CAM】HELLO WORLD
python
大飞pkz15 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
Doris_202315 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202316 小时前
Python 模式匹配match case
前端·后端·python