使用Python小技巧(精华篇)

Python语言目前可谓是非常流行,在目前的语言中很接近自然语言,抽象度非常高,下面,我整理了30个Python小技巧,帮助大家更好的了解和学习Python,欢迎收藏、关注,点赞支持!

▍1、for循环中的else条件

这是一个for-else方法,循环遍历列表时使用else语句。下面举个例子,比如我们想检查一个列表中是否包含奇数。那么可以通过for循环,遍历查找。

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语句。

▍2、从列表中获取元素,定义多个变量

my_list = [1, 2, 3, 4, 5]
one, two, three, four, five = my_list

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

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、将列表中的所有元素作为参数传递给函数

我们可以使用 * 号,提取列表中所有的元素

my_list = [1, 2, 3, 4]

print(my_list)  # [1, 2, 3, 4]
print(*my_list)  # 1 2 3 4

如此便可以将列表中的所有元素,作为参数传递给函数

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、获取列表的所有中间元素

_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]
print(elements_in_the_middle)  # [2, 3, 4, 5, 6, 7]

▍6、使用一行代码赋值多个变量

one, two, three, four = 1, 2, 3, 4

▍7、列表推导式

只用一行代码,便可完成对数组的迭代以及运算。比如,将列表中的每个数字提高一倍。

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num * num for num in numbers]
print(squared_numbers) # [1, 4, 9, 16, 25]

推导式不仅列表能用,字典、集合、生成器也能使用。下面看一下,使用字典推导式,将字典的值提高一倍。

dictionary = {'a': 4, 'b': 5}
squared_dictionary = {key: num * num for (key, num) in dictionary.items()}
print(squared_dictionary)  # {'a': 16, 'b': 25}

▍8、通过Enum枚举同一标签或一系列常量的集合

枚举是绑定到唯一的常量值的一组符号名称(成员)。在枚举中,成员可以通过身份进行比较,枚举本身可以迭代。

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、重复字符串

name = "Banana"
print(name * 4)  # BananaBananaBananaBanana

▍10、比较3个数字的大小

如果想比较一个值和其他两个值的大小情况,你可以使用简单的数学表达式。

1 < x < 10

这个是最简单的代数表达式,在Python中也是可以使用的。

x = 3

print(1 < x < 10)  # True
print(1 < x and x < 10)  # True

▍11、使用1行代码合并字典

first_dictionary = {'name': 'Fan', 'location': 'Guangzhou'}
second_dictionary = {'name': 'Fan', 'surname': 'Xiao', 'location': 'Guangdong, Guangzhou'}

result = first_dictionary | second_dictionary

print(result)
# {'name': 'Fan', 'location': 'Guangdong, Guangzhou', 'surname': 'Xiao'}

▍12、查找元组中元素的索引

books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')
print(books.index('Mastery'))   # 3

▍13、将字符串转换为字符串列表

假设你在函数中获得输出,原本应该是一个列表,但实际上却是一个字符串。

input = "[1,2,3]"

你可能第一时间会想到使用索引或者正则表达式。实际上,使用ast模块的literal_eval方法就能搞定。

import ast

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

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

▍14、计算两数差值

计算出2个数字之间的差值。

def subtract(a, b):
    return a - b
print((subtract(1, 3)))  # -2
print((subtract(3, 1)))  # 2

上面的这个方法,需要考虑数值的先后顺序。

def subtract(a, b):
    return a - b

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

使用命名参数,安排顺序,这样就不会出错了。

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

print(1, 2, 3, "a", "z", "this is here", "here is something else")

▍16、在同一行打印多个元素

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、打印多个值,在每个值之间使用自定义分隔符

print("29", "01", "2022", sep="/")  # 29/01/2022

print("name", "domain.com", sep="@")  # name@domain.com

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

four_letters = "abcd" # this works
4_letters = "abcd" # this doesn’t work

这是Python的变量命名规则。

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

+variable = "abcd"  # this doesn’t work

▍20、数字的第一位不能是0

number = 0110 # this doesn't work

这个确实挺神奇的。

▍21、在变量名的任何地方使用下划线

a______b = "abcd"  # this works
_a_b_c_d = "abcd"  # this also works

这并不意味着,你可以无限使用,为了代码的易读性,还是需要合理使用。

▍22、使用下划线分割数值较大的数字

print(1_000_000_000)  # 1000000000
print(1_234_567)  # 1234567

如此,看到一大堆数字时,也能轻松阅读。

▍23、反转列表

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

▍24、使用步进函数对字符串切片

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、反向切片

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、使用开始或结束索引进行切片

my_string = "This is just a sentence"
print(my_string[4:])  # is just a sentence

print(my_string[:3])  # Thi

▍27、/和//的区别

print(3/2)  # 1.5
print(3//2)  # 1

▍28、==和is的区别

is:检查两个变量是否指向同一对象内存中,==:比较两个对象的值

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)  
# True

▍29、合并字典

dictionary_one = {"a": 1, "b": 2}
dictionary_two = {"c": 3, "d": 4}

merged = {**dictionary_one, **dictionary_two}

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

▍30、检查字符串是否大于另一字符串

first = "abc"
second = "def"

print(first < second)  # True

second = "ab"
print(first < second)  # False

很多刚开始接触编程或者接触Python的同学,可以去看一下B站中的免费教程,讲解的还是比较详细的呢!而且会比自己看书学习吸收的会更快一些,当然一定要经常练习哦!

链接:Python入门教程_适合零基础自学的Python教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值