喝杯咖啡的功夫就能学会的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

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

Python进行JSON和Excel文件转换处理指南

《Python进行JSON和Excel文件转换处理指南》在数据交换与系统集成中,JSON与Excel是两种极为常见的数据格式,本文将介绍如何使用Python实现将JSON转换为格式化的Excel文件,... 目录将 jsON 导入为格式化 Excel将 Excel 导出为结构化 JSON处理嵌套 JSON: