100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习

2021年11月8日21:42:43 发表评论 723 次浏览
100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
照片由 JexoUnsplash

Python现在非常流行,主要是因为它的简单性和易学性。

你可以将其用于各种任务,例如数据科学和机器学习、Web 开发、脚本编写、自动化等。

有用的Python技巧有哪些?既然这是一篇很长的文章,而且你想在喝完咖啡之前就结束,我们为什么不开始呢?

好的,我们现在开始Python技巧合集,下面是详细的Python技巧排行榜:

1.“for”循环中的“Else”条件

常用的Python技巧有哪些?尽管到目前为止你已经看到了所有 Python 代码,但你可能已经错过了以下“for-else”,这是我几周前第一次看到的。

Ť ^ h的是通过一个列表,其中尽管在列表中有一个迭代,你也有一个“其他”条件,这是相当不寻常的循环的“换别人”的方法。

这不是我在其他编程语言(如 Java、Ruby 或 JavaScript)中看到的。

让我们看一个例子,看看它在实践中的样子。

假设我们正在尝试检查列表中是否没有奇数。

让我们遍历它:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
numbers = [2, 4, 6, 8, 1]

for number in numbers:
    if number % 2 == 1:
        print(number)
        break
else:
    print("No odd numbers")

如果我们找到一个奇数,那么将打印该数字,因为将执行break并且将跳过else分支。

否则,如果从未执行过break,则执行流程将继续执行else分支。

在本例中,我们将打印 1。

2. 使用命名变量从列表中获取元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list

3. 使用模块 heapq 获取列表中的 n 个最大或 n 个最小元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import heapq

scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]

print(heapq.nlargest(3, scores))  # [91, 87, 82]
print(heapq.nsmallest(5, scores))  # [15, 33, 33, 49, 51]

4. 将列表中的值作为方法参数传递

我们可以使用“*”提取列表的所有元素:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_list = [1, 2, 3, 4]
print(my_list)  # [1, 2, 3, 4]

print(*my_list)  # 1 2 3 4

这在我们希望将列表的所有元素作为方法参数传递的情况下会很有帮助:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def sum_of_elements(*arg): 
    total = 0 
    for i in arg: 
        total += i 

    return total 


result = sum_of_elements(*[1, 2, 3, 4]) 
print(result) # 10

5.获取列表中间的所有元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]
print(elements_in_the_middle)  # [2, 3, 4, 5, 6, 7]

6. 在一行中分配多个变量

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
one, two, three, four = 1, 2, 3, 4

7. 列表推导式

你可以以非常全面的方式在一行中循环遍历列表中的元素。

让我们在下面的例子中看到它的作用:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
numbers = [1, 2, 3, 4, 5, 6, 7, 8]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)  # [2, 4, 6, 8]

我们可以对字典、集合和生成器做同样的事情。

让我们看另一个例子,但现在是字典。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
dictionary = {'first_element': 1, 'second_element': 2,
              'third_element': 3, 'fourth_element': 4}
odd_value_elements = {key: num for (key, num) in
                      dictionary.items() if num % 2 == 1}
print(odd_value_elements)  # {'first_element': 1, 'third_element': 3}

这个例子的灵感来自这篇文章

8.通过Enum枚举同一概念的相关项

文档

枚举是一组绑定到唯一值的符号名称。它们类似于全局变量,但它们提供了更有用的 repr()、分组、类型安全和一些其他功能。

下面是一个例子:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from enum import Enum 


class Status(Enum): 
    NO_STATUS = -1 
    NOT_STARTED = 0 
    IN_PROGRESS = 1 
    COMPLETED = 2 


print(Status.IN_PROGRESS.name) # IN_PROGRESS 
print(Status.COMPLETED.value) # 2

9. 重复字符串而不循环

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "Abc" 

print(string * 5) # AbcAbcAbcAbcAbc

10. 像数学一样比较 3 个数字

如果你有一个值并且想要比较它是否在其他两个值之间,那么你可以在 Math 中使用一个简单的表达式:

1 < x < 10

这就是我们在小学学到的代数表达式。但是,你也可以在 Python 中使用相同的表达式。

是的,你听到的是对的。到目前为止,你可能已经对这种形式进行了比较:

1 < x 和 x < 10

为此,你只需要在 Python 中使用以下内容:

1 < x < 10
100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习

这在 Ruby 中是行不通的,Ruby 是为了让程序员开心而开发的编程语言。事实证明,这也适用于 JavaScript。

看到如此简单的表达没有被更广泛地谈论,我真的很感动。至少,我没有看到它被提及那么多。

11. 将字典合并在一个可读的行中

这从 Python 3.9 开始可用:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
first_dictionary = {'name': 'Fatos', 'location': 'Munich'} 
second_dictionary = {'name': 'Fatos', 'surname': 'Morina', 
                     'location': 'Bavaria, Munich'} 
result = first_dictionary | second_dictionary 
print(result)   
# {'name': 'Fatos', 'location': 'Bavaria, Munich', 'surname': 'Morina'}

12. 查找元组中元素的索引

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')

print(books.index('Mastery'))   # 3

13. 将字符串转换为字符串列表

假设你在一个字符串函数中获得输入,但它应该是一个列表:

input = "[1,2,3]"

你不需要那种格式。你需要它是一个列表:

input = [1,2,3]

或者,你可能会从 API 调用中得到以下响应:

input = [[1, 2, 3], [4, 5, 6]]

与其费心处理复杂的正则表达式,你只需导入模块ast,然后调用其方法literal_eval

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import ast 


def string_to_list(string): 
    return ast.literal_eval(string)

这就是你需要做的。

现在你将得到一个列表或列表列表的结果,如下所示:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import ast

def string_to_list(string):
    return ast.literal_eval(string)

string = "[[1, 2, 3],[4, 5, 6]]"
my_list = string_to_list(string)
print(my_list)  # [[1, 2, 3], [4, 5, 6]]

14. 使用命名参数避免“琐碎”错误

假设你想找出 2 个数字之间的差值。差异不是可交换的:

a - b != b -a

但是,我们可能会忘记参数的顺序,这可能会导致“微不足道”的错误:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
defsubtract(a, b): 
    return a - b 


print((subtract(1, 3))) # -2 
print((subtract(3, 1))) # 2

为了避免这种潜在的错误,我们可以简单地使用命名参数,参数的顺序不再重要:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def subtract(a, b):
    return a - b


print((subtract(a=1, b=3)))  # -2
print((subtract(b=3, a=1)))  # -2

15. 用一个 print() 语句打印多个元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(1, 2, 3, "a", "z", "this is here", "here is something else")

16.有用的Python技巧有哪些?在同一行打印多个元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print("Hello", end="")
print("World")  # HelloWorld
print("Hello", end=" ")
print("World")  # Hello World
print('words',   'with', 'commas', 'in', 'between', sep=', ')
# words, with, commas, in, between

17. 在每个值之间使用自定义分隔符打印多个值

你可以非常轻松地进行高级打印:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print("29", "01", "2022", sep="/")  # 29/01/2022
print("name", "domain.com", sep="@")  # name@domain.com

18. 不能在变量名的开头使用数字

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
four_letters = “abcd” # this works
4_letters = “abcd” # this doesn’t work

19. 不能在变量名的开头使用运算符

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
+variable = “abcd”  # this doesn’t work

20.Python技巧合集:数字的第一位不能是0

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
number = 0110 # 这不起作用

21. 你可以在变量名的任何地方使用下划线

这意味着,在你想要的任何地方,在变量名称中多次:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
a__b = "abcd" # 这有效
_a_b_c_d = "abcd" # 这也有效

我不鼓励你使用它,但是如果你看到这样一个奇怪的变量命名,请知道它实际上是一个有效的变量名称。

22.你可以用下划线分隔大数字

这样可以更容易地阅读它们。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(1_000_000_000)  # 1000000000
print(1_234_567)  # 1234567

23.颠倒列表的顺序

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_list = ['a', 'b', 'c', 'd'] 

my_list.reverse() 

print(my_list) # ['d', 'c', 'b', 'a']

24. 使用阶跃函数对字符串进行切片

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_string = "This is just a sentence"
print(my_string[0:5])  # This

# Take three steps forward
print(my_string[0:10:3])  # Tsse

25.反向切片

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_string = "This is just a sentence"
print(my_string[10:0:-1])  # suj si sih

# Take two steps forward
print(my_string[10:0:-2])  # sjs i

26. 只使用开始或结束索引的部分切片

指示切片开始结束的索引可以是可选的。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_string = "This is just a sentence"
print(my_string[4:])  # is just a sentence

print(my_string[:3])  # Thi

27.楼层划分

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(3/2)  # 1.5
print(3//2)  # 1

28. == 和“是”的区别

“is”检查两个变量是否指向内存中的同一个对象。

“==”比较这两个对象所持有的值的相等性。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
first_list = [1, 2, 3] 
second_list = [1, 2, 3] 

# 它们的实际值一样吗?
print(first_list == second_list) # True 

# 它们是否指向内存中的同一个对象
print(first_list is second_list)   
# False,因为它们具有相同的值,但是在内存中的不同对象中


third_list = first_list 

print(third_list is first_list)   
#是的,因为两者都指向内存中的同一个对象

29.快速合并2个字典

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
dictionary_one = {"a": 1, "b": 2} 
dictionary_two = {"c": 3, "d": 4} 

merge = {**dictionary_one, **dictionary_two} 

print(merged) # {'a' : 1, 'b': 2, 'c': 3, 'd': 4}

30.检查一个字符串是否大于另一个字符串

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
first = "abc" 
second = "def" 
print(first < second) # True 
second = "ab" 
print(first < second) # False

31.检查字符串是否以特定字符开头而不使用索引0

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_string = "abcdef" 
print(my_string.startswith("b")) # False

32. 使用 id() 查找变量的唯一 id

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(id(1))  # 4325776624
print(id(2))  # 4325776656
print(id("string"))  # 4327978288

33. 整数、浮点数、字符串、布尔值和元组是不可变的

当我们将一个变量分配给一个不可变类型,例如整数、浮点数、字符串、布尔值和元组时,这个变量指向内存中的一个对象。

如果我们为该变量分配另一个值,原始对象仍在内存中,但指向它的变量丢失了:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
number = 1 
print(id(number)) # 4325215472 
print(id(1)) # 4325215472 

number = 3 
print(id(number)) # 4325215536 
print(id(1)) # 4325215472

34. 字符串和元组是不可变的

Python技巧排行榜:这在上一点中已经提到过,但想强调一下,因为这非常重要。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
name = "Fatos" 
print(id(name)) # 4422282544name = "fatos" 
print(id(name)) # 4422346608
100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_tuple = (1, 2, 3, 4) 
print(id(my_tuple)) # 4499290128 

my_tuple = ('a', 'b') 
print(id(my_tuple)) # 4498867584

35. 列表、集合和字典是可变的

常用的Python技巧有哪些?这意味着我们可以在不丢失绑定的情况下更改对象:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
cities = ["Munich", "Zurich", "London"]
print(id(cities))  # 4482699712

cities.append("Berlin")
print(id(cities))  # 4482699712

这是另一个带有集合的示例:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_set = {1, 2, 3, 4}
print(id(my_set))  # 4352726176
my_set.add(5)
print(id(my_set))  # 4352726176

36.你可以把一个集合变成一个不可变的集合

这样,你就无法再修改它:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_set =frozenset(['a', 'b', 'c', 'd']) 

my_set.add("a")

如果这样做,将引发错误:

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

37.一个“if-elif”块可以在没有else块的末尾存在

但是,“elif”不能在没有“if”步骤之前独立存在:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def check_number(number): 
    if number > 0: 
        return "Positive" 
    elif number == 0: 
        return "Zero" 

    return "Negative" 


print(check_number(1)) # Positive

38.使用sorted()检查2个字符串是否为字谜

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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字符的值

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(ord("A")) # 65 
print(ord("B")) # 66 
print(ord("C")) # 66 
print(ord("a")) # 97

40. 在一行中获取字典的键

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
dictionary = {"a": 1, "b": 2, "c": 3}

keys = dictionary.keys()

print(list(keys))  # ['a', 'b', 'c']

41. 在一行中获取字典的值

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
dictionary = {"a": 1, "b": 2, "c": 3}

values = dictionary.values()

print(list(values))  # [1, 2, 3]

42. 交换字典的键和值

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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.你可以将布尔值转换为数字

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(int(False)) # 0 
print(float(True)) # 1.0

44. 你可以在算术运算中使用布尔值

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
x = 10
y = 12
result = (x - False)/(y * True)
print(result)  # 0.8333333333333334

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(bool(.0))  # False
print(bool(3))  # True
print(bool("-"))  # True
print(bool("string"))  # True
print(bool(" "))  # True

46. 有用的Python技巧有哪些?将值转换为复数

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(complex(10, 2))  # (10+2j)

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(hex(11))  # 0xb

47.在列表的第一个位置添加一个值

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

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_list = [3, 4, 5] 

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

48. Lambda 函数只能在一行

不能在多于一行中包含 lambda。

让我们尝试以下操作:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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”部分

让我们尝试以下操作:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
comparison = lambda x: "x > 3" if x > 3

我们将得到以下错误:

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

不,这是条件表达式的一个特性,而不是lambda本身的特性。

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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() 返回一个新对象

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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() 包含一个可能不太为人所知的 step 参数

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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]

53. range() 默认从 0 开始

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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 进行比较:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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.你可以在同一个作用域内多次定义同一个方法 - Python技巧合集

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def get_address():
    return "First address"


def get_address():
    return "Second address"


def get_address():
    return "Third address"


print(get_address())  # Third address

56.你甚至可以访问超出其预期范围的私有属性

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Engineer: 
    def __init__(self, name): 
        self.name = name 
        self.__starting_salary = 62000 


dain = Engineer('Dain') 
print(dain._Engineer__starting_salary) # 62000

57.检查一个对象的内存使用情况

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import sys

print(sys.getsizeof("bitcoin"))  # 56

58.你可以定义一个方法,可以根据需要使用任意多的参数调用

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def get_sum(*arguments): 
    result = 0 
    for i in arguments: 
        result += i 
    return result 


print(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()调用父类的初始值设定项:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Parent: 
    def __init__(self, city, address): 
        self.city = city 
        self.address = address 


class Child(Parent): 
    def __init__(self, city, address, university): 
        super().__init__(city, address ) 
        self.university = university 


child = Child('Zürich', 'Rämistraße 101', 'ETH Zürich') 
print(child.university) # ETH Zürich

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Parent: 
    def __init__(self, city, address): 
        self.city = city 
        self.address = address 


class Child(Parent): 
    def __init__(self, city, address, university): 
        Parent.__init__(self, city, address ) 
        self.university = university 


child = Child('Zürich', 'Rämistraße 101', 'ETH Zürich') 
print(child.university) # ETH Zürich

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

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

每当你在两个int数据类型之间使用+运算符时,你都会找到它们的总和。

但是,当你在两种字符串数据类型之间使用它时,你将合并它们:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(10 + 1)  # Adding two integers using '+'
print('first' + 'second')  # Merging two strings '+'

这表示运算符重载

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Expenses: 
    def __init__(self,rent,groceries): 
        self.rent =rent 
        self.groceries = groceries 

    def __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. 你也可以在你自己的类中重新定义“<”和“==”操作符

常用的Python技巧有哪些?这是你可以自己定义的操作重载的另一个示例:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Game: 
    def __init__(self, score): 
        self.score = score 

    def __lt__(self, other): 
        return self.score < other.score 


first = Game(1) 
second = Game(2) 

print(first < second) # True

同理,和前面两种情况一样,我们可以根据自己的需要重写__eq__()函数:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Journey:
    def __init__(self, location, destination, duration):
        self.location = location
        self.destination = destination
        self.duration = duration

    def __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__() 用于-
  • __mul__() 为*
  • __truediv __() 为/
  • __ne __ () 为! =
  • __ge__() 为 >=
  • __gt__() 用于 >

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class Rectangle:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return repr('Rectangle with area=' + str(self.a * self.b))


print(Rectangle(3, 4))  # 'Rectangle with area=12'

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "This is just a sentence."
result = string.swapcase()
print(result)  # tHIS IS JUST A SENTENCE.

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "  "
result = string.isspace()
print(result)  # True

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
name = "Password"
print(name.isalnum())  # True, because all characters are alphabets
name = "Secure Password "
print(name.isalnum())  # False, because it contains whitespaces
name = "S3cur3P4ssw0rd"
print(name.isalnum())  # True
name = "133"
print(name.isalnum())  # True, because all characters are numbers

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "Name"
print(string.isalpha())  # True
string = "Firstname Lastname"
print(string.isalpha())  # False, because it contains whitespace
string = “P4ssw0rd”
print(string.isalpha())  # False, because it contains numbers

67.根据参数从右边删除字符

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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"

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "ffffffffFirst"
print(string.lstrip(“f”))  # First

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "seven"
print(string.isdigit())  # False
string = "1337"
print(string.isdigit())  # True
string = "5a"
print(string.isdigit())  # False, because it contains the character 'a'
string = "2**5"
print(string.isdigit())  # False

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
# 42673 in Arabic numerals
string = "四二六七三"

print(string.isdigit())  # False
print(string.isnumeric())  # True

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "This is a sentence"
print(string.istitle())  # False

string = "10 Python Tips"
print(string.istitle())  # True

string = "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.我们也可以在元组中使用负索引

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
numbers = (1, 2, 3, 4)

print(numbers[-1])  # 4
print(numbers[-4])  # 1

72. 在元组中嵌套一个列表和一个元组 - Python技巧合集

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
mixed_tuple = (("a"*10, 3, 4), ['first', 'second', 'third'])

print(mixed_tuple[1])  # ['first', 'second', 'third']
print(mixed_tuple[0])  # ('aaaaaaaaaa', 3, 4)

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
names = ["Besim", "Albert", "Besim", "Fisnik", "Meriton"] 

print(names.count("Besim")) # 2

74. 你可以使用 slice() 轻松获取最后 n 个元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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()用于其他常见的切片任务,例如:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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.计算元素在元组中出现的次数

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_tuple = ('a', 1, 'f', 'a', 5, 'a') 

print(my_tuple.count('a')) # 3

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_tuple = ('a', 1, 'f', 'a', 5, 'a')
print(my_tuple.index('f'))  #  2

77. 通过跳转获得子元组

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(my_tuple[::3])  # (1, 4, 7, 10)

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
print(my_tuple[3:])  # (4, 5, 6, 7, 8, 9, 10)

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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.连接两个集合:有用的Python技巧有哪些?

一种方法是使用方法union()作为连接的结果返回一个新集合:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
first_set = {4, 5, 6} 
second_set = {1, 2, 3} 

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

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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. Python技巧排行榜 - 打印函数内部的条件

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
def is_positive(number): 
    print("Positive" if number > 0 else "Negative") # Positive 


is_positive(-3)

82. 单个 if 语句中的多个条件

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
math_points = 51
biology_points = 78
physics_points = 56
history_points = 72

my_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 语句中,至少满足多个条件中的一个

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
math_points = 51
biology_points = 78
physics_points = 56
history_points = 72

my_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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(bool("Non empty"))  # True
print(bool(""))  # False

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(bool([])) # False 
print(bool(set([]))) # False 

print(bool({})) # False 
print(bool({"a": 1})) # True

86. 评估为 False 的其他值是 None、“​​False”和数字 0

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
print(bool(False)) # False 
print(bool(None)) # False 
print(bool(0)) # False

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "string" 


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


do_nothing() 

print(string) # string

你还需要使用访问修饰符global

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
string = "string" 


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


do_nothing() 

print(string) # 在方法内

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from collections import Counter 

result = 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 个字符串是否为字谜

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from collections import Counter 


def 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()检查 2 个字符串是否为字谜:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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”计算元素的数量

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from itertools import count

my_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不会根据元素的频率对元素进行排序。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from collections import Counter 

result = 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. 在一行中找到列表中出现频率最高的元素

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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() 的示例:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
first_list = [[1, 2, 3], ['a', 'b', 'c']] 

second_list = first_list.copy() 

first_list[0][2] = 831 

print(first_list) # [[1, 2, 831], ['a', 'b', 'c']] 
print(second_list) # [[1, 2, 831], ['a', 'b', 'c']]

这是 deepcopy() 案例的示例:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import copy 

first_list = [[1, 2, 3], ['a', 'b', 'c']] 

second_list = copy.deepcopy(first_list) 

first_list[0][2] = 831 

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

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

常用的Python技巧有哪些?如果你使用普通字典并尝试访问一个不存在的键,那么你将收到一个错误:

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_dictonary = {"name": "Name", "surname": "Surname"}
print(my_dictonary["age"])  

这是抛出的错误:

KeyError: 'age'

我们可以使用defaultdict()避免此类错误

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
from collections import defaultdict 

my_dictonary = defaultdict(str) 
my_dictonary['name'] = "Name" 
my_dictonary['surname'] = "Surname" 

print(my_dictonary["age"])  

95.Python技巧排行榜 - 你可以构建自己的迭代器

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
class OddNumbers: 
    def __iter__(self): 
        self.a = 1 
        return self 

    def __next__(self): 
        x = self.a 
        self.a += 2 
        return 


xodd_numbers_object = OddNumbers() 
iterator = iter(odd_numbers_object) 

print(next( iterator)) # 1 
print(next(iterator)) # 3 
print(next(iterator)) # 5

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
my_set = set([1, 2, 1, 2, 3, 4, 5]) 
print(list(my_set)) # [1, 2, 3, 4, 5]

97.打印一个模块所在的地方

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import torch 

print(torch) # <module 'torch' from '/Users/...'

98. 你可以使用“not in”检查一个值是否不在列表中

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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. 有用的Python技巧有哪些?sort() 和 sorted() 的区别

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

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

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
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 代表通用唯一标识符。

100个有用的 Python技巧合集,你可以在喝完早间咖啡之前学习
import uuid 

# 根据主机 ID、序列号和当前时间生成 UUID 
print(uuid.uuid1()) # 308490b6-afe4-11eb-95f7-0c4de9a0c5af 

# 生成随机 UUID 
print(uuid.uuid4()) # 93bc700b-253e-4081-a358-24b60591076a

奖励:101. 字符串是 Python 中的原始数据类型

Python技巧合集:如果你有 Java 背景,就会知道 Java 中的 String 是一种非原始数据类型,因为它指的是一个对象。

在 Python 中,字符串是一种原始数据类型。

我希望你至少从这篇文章中学到了一些东西。

快乐编码!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: