【Python】8个非常有用的Python单行代码

本文介绍了如何在Python中使用一行代码进行多变量赋值、删除列表重复项、过滤列表值、编写if...else语句、for循环、while循环以及合并字典和定义函数的方法。通过set去重、filter函数过滤偶数、三元运算符简化条件判断等技巧,展示了Python的简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多变量赋值

a, b, c = 2, 3.3, 'python'
print(a, b, c)  #结果: 2 3.3 python

a, b, *c = [1, 2,3, 4, 5]
print(a, b, c)  #结果: 1 2 [3, 4, 5]

删除列表中的重复项

使用set来消除重复项。set是一种无序集合,其中每个元素都是唯一的。这意味着如果我们将列表变成一个集合,就可以快速删除重复项,。然后我们只需要将集合再次转换为列表即可。

numbers = [1, 1, 1, 2, 2, 3, 4, 5, 5]
print(list(set(numbers)))   #结果:[1, 2, 3, 4, 5]

从列表中过滤值

使用 filter() 函数。语法:filter(function, iterable)。在过滤器函数中添加一个lambda函数,效果更好!
案例:过滤出列表[10, 15, 17, 34]中的偶数。

my_list = [10, 15, 17, 34]
print(list(filter(lambda x: x%2 ==0, my_list))) #结果:[10, 34]

一行if…else语句

要在一行中编写if…else语句,我们将使用三元运算符。三元的语法是[on true] if [expression] else [on false]

# 单条件
score = 97
if score > 90: print("Excellent")    # Excellent

# 双条件
print("Excellent") if score > 90 else print("Great")

# 多条件
print("Excellent") if score > 90 else print("Great") if score > 80 else print("Good")

一行for循环

for循环是一个多行语句,但是在Python中,我们可以使用列表推导式方法在一行中编写for循环。
案例:过滤出列表[0, 5, 12, 34]中大于10的值。

mylist = [0, 5, 12, 34]
# 正常解法
result = []
for i in mylist:
    if i > 10:
        result.append(i)
print(result)   # [12, 34]

# 一行代码
result = [i for i in mylist if i > 10]
print(result)   # [12, 34]

一行while循环

# 单语句
while True: print("Done")   # 死循环

# 多语句
i = 0
while i < 5: print(i); i+=1     # 0 1 2 3 4 

一行合并字典

d1 = {'A': 1, 'B': 2}
d2 = {'C': 3, 'D': 4}
# 方法1:
d1.update(d2)
print(d1)   # {'A': 1, 'B': 2, 'C': 3, 'D': 4}

# 方法2:使用解包运算符 **
d3 = {**d1, **d2}
print(d3)   # {'A': 1, 'B': 2, 'C': 3, 'D': 4}

一行函数

# 方法1:使用与三元运算符或单行循环方法相同的函数定义
def fun(x): return True if x % 2 == 0 else False
print(fun(3))   # False

# 方法2:使用lambda定义函数
fun = lambda x: x % 2 == 0
print(fun(6))   # True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值