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

2024-06-21 08:08

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

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

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


作者:Fatos Morina

编译:ronghuaiyang

导读

接上一篇,34~66条。

34. Strings 和 tuples 是不可修改的

这一点在上一点中已经提到过,但我想强调一下,因为这是非常重要的。

name = "Fatos"
print(id(name))  # 4422282544name = "fatos"
print(id(name))  # 4422346608
my_tuple = (1, 2, 3, 4)
print(id(my_tuple))  # 4499290128my_tuple = ('a', 'b')
print(id(my_tuple))  # 4498867584

35. Lists, sets, 和 dictionaries 是不可修改的

这意味着我们可以在不丢失绑定的情况下更改对象:

cities = ["Munich", "Zurich", "London"]
print(id(cities))  # 4482699712cities.append("Berlin")
print(id(cities))  # 4482699712

下面是另一个集合的例子:

my_set = {1, 2, 3, 4}
print(id(my_set))  # 4352726176my_set.add(5)
print(id(my_set))  # 4352726176

36. 你可以把集合转换为不可修改的集合

这样,你就不能再修改它了:

my_set = frozenset(['a', 'b', 'c', 'd'])my_set.add("a")

如果你这样做,就会抛出一个错误:

AttributeError: 'frozenset' object has no attribute 'add'

37. " if-elif "块可以在没有else块的情况下存在

但是,如果前面没有“if”,“elif”就不能独立存在:

def check_number(number):if number > 0:return "Positive"elif number == 0:return "Zero"return "Negative"print(check_number(1))  # Positive

38. 使用sorted()查看2个字符串是否是相同的字母但次序不一样

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

39. 获取一个字符的Unicode值

print(ord("A"))  # 65
print(ord("B"))  # 66
print(ord("C"))  # 66
print(ord("a"))  # 97

40. 一行代码获取字典中所有的keys

dictionary = {"a": 1, "b": 2, "c": 3}keys = [i for i, _ in dictionary.items()]print(keys)  # ['a', 'b', 'c']

41. 一行代码获取字典中所有的值

dictionary = {"a": 1, "b": 2, "c": 3}values = [i for _, i in dictionary.items()]print(values)  # [1, 2, 3]

42. 交换字典中的keys和values

dictionary = {"a": 1, "b": 2, "c": 3}reversed_dictionary = {j: i for i, j in dictionary.items()}print(reversed)  # {1: 'a', 2: 'b', 3: 'c'}

43. 你可以将布尔型值转换为数字

print(int(False))  # 0
print(float(True))  # 1.0

44. 你可以算术操作中使用布尔值

“False”是0,而“True”是1。

x = 10
y = 12
result = (x - False)/(y * True)
print(result)  # 0.8333333333333334

45. 你可以将任何数据的类型转换为布尔值

print(bool(.0))  # False
print(bool(3))  # True
print(bool("-"))  # True
print(bool("string"))  # True
print(bool(" "))  # True

46. 将一个值转换为复数

print(complex(10, 2))  # (10+2j)

也可以将数字转换为十六进制数:

print(hex(11))  # 0xb

47. 把值加到列表的第一个位置

如果你使用append(),你将从右边插入新的值。

也可以使用*insert()*来指定要插入新元素的索引和元素。在我们的例子中,我们想把它插入到第一个位置,所以我们使用0作为下标:

my_list = [3, 4, 5]my_list.append(6)
my_list.insert(0, 2)
print(my_list)  # [2, 3, 4, 5, 6]

48. Lambda方法只能在一行里

在使用lambdas方法的时候,不能超过一行。

让我们试试以下方法:

comparison = lambda x: if x > 3:print("x > 3")else:print("x is not greater than 3")

将抛出以下错误:

result = lambda x: if x > 3:^
SyntaxError: invalid syntax

49. lambda中的条件语句应该始终包含“else”部分

我们试下下面的:

comparison = lambda x: "x > 3" if x > 3

我们将得到以下错误:

comparison = lambda x: "x > 3" if x > 3^
SyntaxError: invalid syntax

50. filter() 返回一个新的对象

my_list = [1, 2, 3, 4]odd = filter(lambda x: x % 2 == 1, my_list)print(list(odd))   # [1, 3]
print(my_list)  # [1, 2, 3, 4]

51. map() 返回一个新的对象

my_list = [1, 2, 3, 4]squared = map(lambda x: x ** 2, my_list)print(list(squared))   # [1, 4, 9, 16]
print(my_list)  # [1, 2, 3, 4]

52. range() 中有一个步长的参数,但是知道的并不多

for number in range(1, 10, 3):print(number, end=" ")
# 1 4 7

53. range() 默认从0开始

所以你根本不需要包含它。

def range_with_zero(number):for i in range(0, number):print(i, end=' ')def range_with_no_zero(number):for i in range(number):print(i, end=' ')range_with_zero(3)  # 0 1 2
range_with_no_zero(3)  # 0 1 2

54. 不需要将长度和0比较

如果长度大于0,则默认为True,所以你不需要将其与0进行比较:

def get_element_with_comparison(my_list):if len(my_list) > 0:return my_list[0]def get_first_element(my_list):if len(my_list):return my_list[0]elements = [1, 2, 3, 4]
first_result = get_element_with_comparison(elements)
second_result = get_element_with_comparison(elements)print(first_result == second_result)  # True

55. 可以在同一范围内多次定义相同的方法

但是,只有最后一个被调用,因为它覆盖了以前的。

def get_address():return "First address"def get_address():return "Second address"def get_address():return "Third address"print(get_address())  # Third address

56. 你可以访问私有属性

class Engineer:def __init__(self, name):self.name = nameself.__starting_salary = 62000dain = Engineer('Dain')
print(dain._Engineer__starting_salary)  # 62000

57. 查看对象的内存使用

import sysprint(sys.getsizeof("bitcoin"))  # 56

58. 定义一个方法,调用的时候想传多少参数都可以

def get_sum(*arguments):result = 0for i in arguments:result += ireturn resultprint(get_sum(1, 2, 3))  # 6
print(get_sum(1, 2, 3, 4, 5))  # 15
print(get_sum(1, 2, 3, 4, 5, 6, 7))  # 28

59. 使用super() 或者父类的名字调用父类的初始化

使用*super()*调用父类初始化器:

class Parent:def __init__(self, city, address):self.city = cityself.address = addressclass Child(Parent):def __init__(self, city, address, university):super().__init__(city, address)self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')
print(child.university)  # ETH Zürich

使用父类的名称调用父类:

class Parent:def __init__(self, city, address):self.city = cityself.address = addressclass Child(Parent):def __init__(self, city, address, university):Parent.__init__(self, city, address)self.university = universitychild = Child('Zürich', 'Rämistrasse 101', 'ETH Zürich')
print(child.university)  # ETH Zürich

注意,使用**init()super()**调用父类初始化器只能在子类的初始化器中使用。

60. 你可以在自己的类中重新定义“+”操作符

当你在两个int数据类型之间使用**+**操作符时,你将得到它们的和。

然而,当你在两个字符串数据类型之间使用它时,你将合并它们:

print(10 + 1)  # Adding two integers using '+'
print('first' + 'second')  # Merging two strings '+'

这表示操作符重载

你也可以在你自己的类中使用它:

class Expenses:def __init__(self, rent, groceries):self.rent = rentself.groceries = groceriesdef __add__(self, other):return Expenses(self.rent + other.rent,self.groceries + other.groceries)april_expenses = Expenses(1000, 200)
may_expenses = Expenses(1000, 300)total_expenses = april_expenses + may_expenses
print(total_expenses.rent)  # 2000
print(total_expenses.groceries)  # 500

61. 你还可以在自己的类中重新定义“<”和“=”操作符Y

下面是另一个你可以自己定义的操作重载的例子:

class Game:def __init__(self, score):self.score = scoredef __lt__(self, other):return self.score < other.scorefirst = Game(1)
second = Game(2)print(first < second)  # True

类似地,就像前面的两种情况,我们可以根据自己的需要重写*eq()*函数:

class Journey:def __init__(self, location, destination, duration):self.location = locationself.destination = destinationself.duration = durationdef __eq__(self, other):return ((self.location == other.location) and(self.destination == other.destination) and(self.duration == other.duration))first = Journey('Location A', 'Destination A', '30min')
second = Journey('Location B', 'Destination B', '30min')print(first == second)

你也可以类似地定义:

  • sub() for -

  • mul() for *****

  • truediv() for /

  • ne() for !=

  • ge() for >=

  • gt() for >

62. 你可以为类的对象定义一个自定义的可打印版本

class Rectangle:def __init__(self, a, b):self.a = aself.b = bdef __repr__(self):return repr('Rectangle with area=' + str(self.a * self.b))print(Rectangle(3, 4))  # 'Rectangle with area=12'

63. 交换字符串中的字符大小写

string = "This is just a sentence."
result = string.swapcase()print(result)  # tHIS IS JUST A SENTENCE.

64. 检查是否所有字符都是字符串中的空格

string = "  "
result = string.isspace()print(result)  # True

65. 检查字符串中的所有字符是否都是字母或数字

name = "Password"
print(name.isalnum())  # True, because all characters are alphabetsname = "Secure Password "
print(name.isalnum())  # False, because it contains whitespacesname = "S3cur3P4ssw0rd"
print(name.isalnum())  # Truename = "133"
print(name.isalnum())  # True, because all characters are numbers

66. 检查字符串中的所有字符是否都是字母

string = "Name"
print(string.isalpha())  # Truestring = "Firstname Lastname"
print(string.isalpha())  # False, because it contains whitespacestring = “P4ssw0rd”
print(string.isalpha())  # False, because it contains numbers

—END—

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

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

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

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



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

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

mtu设置多少网速最快? 路由器MTU设置最佳网速的技巧

《mtu设置多少网速最快?路由器MTU设置最佳网速的技巧》mtu设置多少网速最快?想要通过设置路由器mtu获得最佳网速,该怎么设置呢?下面我们就来看看路由器MTU设置最佳网速的技巧... 答:1500 MTU值指的是在网络传输中数据包的最大值,合理的设置MTU 值可以让网络更快!mtu设置可以优化不同的网

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取