高效的单行python脚本

2023-12-13 13:09:07

#-- coding: utf-8 --
“”"
Created on Wed Dec 6 13:42:00 2023
@author: czliu
“”"

1. 平方列表推导

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

squares = [x**2 for x in range(1, 11)]
print(squares)

2.求偶数

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

even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)

3. 交换变量

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

a=23
b=25
a, b = b, a
print(a,b)

4.反转字符串

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

reversed_string = "Hello, World!"[::-1]
print(reversed_string)

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

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

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 函数根据特定键对字典列表进行排序。

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 从列表中获取唯一元素

original_list = [12,34,12,45,'t','w','w']
unique_elements = list(set(original_list))

8. 检查回文

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

string = 'abcdcba'
is_palindrome = string == string[::-1]
print(is_palindrome)

9. 在 Sentece 中颠倒单词

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

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

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

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

my_string = 'AbcdcBa'
is_palindrome = my_string.lower() == my_string[::-1].lower()
print(is_palindrome)

文章来源:https://blog.csdn.net/qq_43596960/article/details/134830911
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。