喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3)

2024-06-21 08:08

本文主要是介绍喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

点击上方“AI公园”,关注公众号,选择加“星标“或“置顶”

因公众号更改了推送规则,记得读完点“在看”~下次AI公园的新文章就能及时出现在您的订阅列表中


作者:Fatos Morina

编译:ronghuaiyang

导读

接上一篇,67~100条。

67. 根据参数从右侧移除字符

string = "This is a sentence with "
# Remove trailing spaces from the right
print(string.rstrip())  # "This is a sentence with"
string = "this here is a sentence…..,,,,aaaaasd"
print(string.rstrip(“.,dsa”))  # "this here is a sentence"

类似地,你可以根据参数从左边删除字符:

string = "ffffffffFirst"
print(string.lstrip(“f”))  # First

68. 检查一个字符串是否代表一个数字

string = "seven"
print(string.isdigit())  # Falsestring = "1337"
print(string.isdigit())  # Truestring = "5a"
print(string.isdigit())  # False, because it contains the character 'a'string = "2**5"
print(string.isdigit())  # False

69. 检查一个字符串是否代表一个中文数字

# 42673 in Arabic numerals
string = "四二六七三"print(string.isdigit())  # False
print(string.isnumeric())  # True

70. 检查一个字符串是否所有的单词都以大写字母开头

string = "This is a sentence"
print(string.istitle())  # Falsestring = "10 Python Tips"
print(string.istitle())  # Truestring = "How to Print A String in Python"
# False, because of the first characters being lowercase in "to" and "in"
print(string.istitle())string = "PYTHON"
print(string.istitle())  # False. It's titlelized version is "Python"

71. 我们也可以在元组中使用负索引

numbers = (1, 2, 3, 4)print(numbers[-1])  # 4
print(numbers[-4])  # 1

72. 在元组中嵌套列表和元组

mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])print(mixed_tuple[1])  # ['first', 'second', 'third']
print(mixed_tuple[0])  # ('aaaaaaaaaa', 3, 4)

73. 快速计算满足条件的元素在列表中出现的次数

names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"]print(names.count("Besim"))  # 2

74. 使用slice()可以方便的得到最近的元素

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slicing = slice(-4, None)# Getting the last 3 elements from the list
print(my_list[slicing])  # [4, 5, 6]# Getting only the third element starting from the right
print(my_list[-3])  # 4

你也可以使用*slice()*来完成其他常见的切片任务,比如:

string = "Data Science"# start = 1, stop = None (don't stop anywhere), step = 1
# contains 1, 3 and 5 indices
slice_object = slice(5, None)print(string[slice_object])   # Science

75. 计算元素在元组中出现的次数

my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.count('a'))  # 3

76. 获取元组中元素的索引

my_tuple = ('a', 1, 'f', 'a', 5, 'a')print(my_tuple.index('f'))  #  2

77. 通过跳转获取子元组

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[::3])  # (1, 4, 7, 10)

78. 从索引开始获取子元组

my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)print(my_tuple[3:])  # (4, 5, 6, 7, 8, 9, 10)

79. 从列表、集合或字典中删除所有元素

my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)  # []my_set = {1, 2, 3}
my_set.clear()
print(my_set)  # set()my_dict = {"a": 1, "b": 2}
my_dict.clear()
print(my_dict)  # {}

80. 合并2个集合

一种方法是使用方法union(),它将作为合并的结果返回一个新的集合:

first_set = {4, 5, 6}
second_set = {1, 2, 3}print(first_set.union(second_set))  # {1, 2, 3, 4, 5, 6}

另一个是方法update,它将第二个集合的元素插入到第一个集合中:

first_set = {4, 5, 6}
second_set = {1, 2, 3}first_set.update(second_set)print(first_set)  # {1, 2, 3, 4, 5, 6}

81. 打印函数内的条件语句

def is_positive(number):print("Positive" if number > 0 else "Negative")  # Positiveis_positive(-3)

82. 一个if语句中包含多个条件

math_points = 51
biology_points = 78
physics_points = 56
history_points = 72my_conditions = [math_points > 50, biology_points > 50,physics_points > 50, history_points > 50]if all(my_conditions):print("Congratulations! You have passed all of the exams.")
else:print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.

83. 在一个if语句中至少满足一个条件

math_points = 51
biology_points = 78
physics_points = 56
history_points = 72my_conditions = [math_points > 50, biology_points > 50,physics_points > 50, history_points > 50]if any(my_conditions):print("Congratulations! You have passed all of the exams.")
else:print("I am sorry, but it seems that you have to repeat at least one exam.")
# Congratulations! You have passed all of the exams.

84. 任何非空字符串都被计算为True

print(bool("Non empty"))  # True
print(bool(""))  # False

85. 任何非空列表、元组或字典都被求值为True

print(bool([]))  # False
print(bool(set([])))  # Falseprint(bool({}))  # False
print(bool({"a": 1}))  # True

86. 其他计算为False的值是None、“False”和数字0

print(bool(False))  # False
print(bool(None))  # False
print(bool(0))  # False

87. 你不能仅仅通过在函数中提及全局变量来改变它的值

string = "string"def do_nothing():string = "inside a method"do_nothing()print(string)  # string

你也需要使用访问修饰符global:

string = "string"def do_nothing():global stringstring = "inside a method"do_nothing()print(string)  # inside a method

88. 使用“collections”中的Counter计算字符串或列表中的元素数量

from collections import Counterresult = Counter("Banana")
print(result)  # Counter({'a': 3, 'n': 2, 'B': 1})result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])
print(result)  # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

89. 使用Counter检查是否2个字符串包含相同的字符

from collections import Counterdef check_if_anagram(first_string, second_string):first_string = first_string.lower()second_string = second_string.lower()return Counter(first_string) == Counter(second_string)print(check_if_anagram('testinG', 'Testing'))  # True
print(check_if_anagram('Here', 'Rehe'))  # True
print(check_if_anagram('Know', 'Now'))  # False

你也可以使用*sorted()*检查两个字符串是否具有相同的字符:

def check_if_anagram(first_word, second_word):first_word = first_word.lower()second_word = second_word.lower()return sorted(first_word) == sorted(second_word)print(check_if_anagram("testinG", "Testing"))  # True
print(check_if_anagram("Here", "Rehe"))  # True
print(check_if_anagram("Know", "Now"))  # False

90. 使用" itertools "中的" Count "计算元素的数量

from itertools import countmy_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']current_counter = count()string = "This is just a sentence."for i in string:if i in my_vowels:print(f"Current vowel: {i}")print(f"Number of vowels found so far: {next(current_counter)}")

这是控制台中的结果:

Current vowel: i
Number of vowels found so far: 0
Current vowel: i
Number of vowels found so far: 1
Current vowel: u
Number of vowels found so far: 2
Current vowel: a
Number of vowels found so far: 3
Current vowel: e
Number of vowels found so far: 4
Current vowel: e
Number of vowels found so far: 5
Current vowel: e
Number of vowels found so far: 6

91. 根据字符串或列表的频率对元素进行排序

来自collections模块的Counter默认情况下不会根据元素的频率来排序。

from collections import Counterresult = Counter([1, 2, 3, 2, 2, 2, 2])
print(result)  # Counter({2: 5, 1: 1, 3: 1})
print(result.most_common())  # [(2, 5), (1, 1), (3, 1)]

92. 在一行中找到列表中出现频次最高的元素

my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']print(max(set(my_list), key=my_list.count))  # a

93. copy()和deepcopy()的区别

来自文档中的解释:

浅拷贝构造一个新的复合对象,然后(在可能的范围内)在其中插入对原始对象的引用。深拷贝构造一个新的复合对象,然后递归地将在原始对象中找到的对象的副本插入其中。

更全面的描述:

浅拷贝意味着构造一个新的集合对象,然后用对原始集合中的子对象的引用填充它。从本质上说,浅拷贝的深度只有一层。拷贝过程不会递归,因此不会创建子对象本身的副本。深拷贝使拷贝过程递归。这意味着首先构造一个新的集合对象,然后用在原始集合对象中找到的子对象的副本递归地填充它。以这种方式拷贝对象将遍历整个对象树,以创建原始对象及其所有子对象的完全独立的克隆。

这里是copy()的例子:

first_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = first_list.copy()first_list[0][2] = 831print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 831], ['a', 'b', 'c']]

这个是deepcopy() 的例子:

import copyfirst_list = [[1, 2, 3], ['a', 'b', 'c']]second_list = copy.deepcopy(first_list)first_list[0][2] = 831print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
print(second_list)  # [[1, 2, 3], ['a', 'b', 'c']]

94. 当试图访问字典中不存在的键时,可以避免抛出错误

如果你使用一个普通的字典,并试图访问一个不存在的键,那么你将得到一个错误:

my_dictonary = {"name": "Name", "surname": "Surname"}print(my_dictonary["age"])  

下面是抛出的错误:

KeyError: 'age'

我们可以使用defaultdict():来避免这种错误

from collections import defaultdictmy_dictonary = defaultdict(str)
my_dictonary['name'] = "Name"
my_dictonary['surname'] = "Surname"print(my_dictonary["age"])  

95. 你可以构建自己的迭代器

class OddNumbers:def __iter__(self):self.a = 1return selfdef __next__(self):x = self.aself.a += 2return xodd_numbers_object = OddNumbers()
iterator = iter(odd_numbers_object)print(next(iterator))  # 1
print(next(iterator))  # 3
print(next(iterator))  # 5

96. 可以用一行从列表中删除重复项

my_set = set([1, 2, 1, 2, 3, 4, 5])
print(list(my_set))  # [1, 2, 3, 4, 5]

97. 打印模块所在的位置

import torchprint(torch)  # <module 'torch' from '/Users/...'

98. 可以使用" not in "来检查值是否不属于列表

odd_numbers = [1, 3, 5, 7, 9]
even_numbers = []for i in range(9):if i not in odd_numbers:even_numbers.append(i)print(even_numbers)  # [0, 2, 4, 6, 8]

99. sort() 和 sorted()的差别

sort()对原始列表进行排序。

sorted()返回一个新的排序列表。

groceries = ['milk', 'bread', 'tea']new_groceries = sorted(groceries)
# new_groceries = ['bread', 'milk', 'tea']print(new_groceries)# groceries = ['milk', 'bread', 'tea']
print(groceries)groceries.sort()# groceries = ['bread', 'milk', 'tea']
print(groceries)

100. 使用uuid模块生成唯一的id

UUID代表统一唯一标识符。

import uuid# Generate a UUID from a host ID, sequence number, and the current time
print(uuid.uuid1())  # 308490b6-afe4-11eb-95f7-0c4de9a0c5af# Generate a random UUID
print(uuid.uuid4())  # 93bc700b-253e-4081-a358-24b60591076a

—END—

英文原文:https://towardsdatascience.com/100-helpful-python-tips-you-can-learn-before-finishing-your-morning-coffee-eb9c39e68958

请长按或扫描二维码关注本公众号

喜欢的话,请给我个在看吧

这篇关于喝杯咖啡的功夫就能学会的100个非常有用的Python技巧(3)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1080666

相关文章

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

基于Python开发一个图像水印批量添加工具

《基于Python开发一个图像水印批量添加工具》在当今数字化内容爆炸式增长的时代,图像版权保护已成为创作者和企业的核心需求,本方案将详细介绍一个基于PythonPIL库的工业级图像水印解决方案,有需要... 目录一、系统架构设计1.1 整体处理流程1.2 类结构设计(扩展版本)二、核心算法深入解析2.1 自

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

Python自动化批量重命名与整理文件系统

《Python自动化批量重命名与整理文件系统》这篇文章主要为大家详细介绍了如何使用Python实现一个强大的文件批量重命名与整理工具,帮助开发者自动化这一繁琐过程,有需要的小伙伴可以了解下... 目录简介环境准备项目功能概述代码详细解析1. 导入必要的库2. 配置参数设置3. 创建日志系统4. 安全文件名处

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

MySQL 多列 IN 查询之语法、性能与实战技巧(最新整理)

《MySQL多列IN查询之语法、性能与实战技巧(最新整理)》本文详解MySQL多列IN查询,对比传统OR写法,强调其简洁高效,适合批量匹配复合键,通过联合索引、分批次优化提升性能,兼容多种数据库... 目录一、基础语法:多列 IN 的两种写法1. 直接值列表2. 子查询二、对比传统 OR 的写法三、性能分析