高效的单行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)
相关推荐
2601_962293241 小时前
Python自动化统计团队工作量并生成可视化仪表盘的脚本方案【指导】
python·数据分析·自动化·可视化·仪表盘
2601_962293793 小时前
OCRmyPDF批处理脚本:使用Python自动化复杂OCR任务
python·自动化·批处理脚本·ocrmypdf·ocr任务
Java后端的Ai之路4 小时前
20、Python - 备忘录模式
开发语言·人工智能·python·外观模式·备忘录模式
嘿嘿-664 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
2601_962077714 小时前
基于Python与NLP的新闻事件信息抽取实战:从NER到时空标准化
python·nlp·transformers·spacy·新闻事件抽取
JavaPub-rodert5 小时前
LangChain 从入门到 Agent 实战:用 Python 搭建一个真正能调用工具和知识库的 AI 助手
人工智能·python·langchain
郝学胜-神的一滴5 小时前
Qt 高级编程 045:坐标体系深度实战
开发语言·c++·windows·python·qt·程序人生
m0_380743876 小时前
给 OpenAI API 调用加上模型切换:GPT-5.1 和 Codex 的配置实践
人工智能·python·gpt
唐青枫6 小时前
别把日志、权限写进业务方法:C#.NET 动态代理从原理到实战
c#·.net
2601_962297486 小时前
在python3中、下列输出变量a的正确写法是_2020超星大数据Python免费答案
数据结构·python·算法·编程·字符串操作