Python单行代码 / 简洁高效

# 一行if else语句。
# 示例1 if else
print("Yes") if 8 > 9 else print("No") # No

# 示例2 if elif else
E = 2
print("High") if E == 5 else print("数据STUDIO") if E == 2 else rint("Low") 

# 示例3 仅if
if 3 > 2: print("Exactly") # Exactly

# 在一行中合并字典
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}

# 单行递归

# Fibonaci单行递归示例
def Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(2)) # 2
print(Fib(5)) # 8
print(Fib(15)) # 987

# 在单行中过滤数组
mylist = [2, 3, 5, 8, 9, 12, 13, 15]

# 正常方式
result = []
for x in mylist:
    if x % 2 == 0:
        result.append(x)
print(result) # [2, 8, 12]

# 单行方法
result = [x for x in mylist if x % 2 == 0]
print(result) # [2, 8, 12]

# 一行字典 使用Python enumerate()函数将列表转换为字典
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}

# 一行多个变量赋值。
# 多行方法
x = 5
y = 7
z = 10
print(x , y, z) # 5 7 10

# 单行方法
a, b, c = 5, 7, 10
print(a, b, c) # 5 7 10

# 在一行中读取文件

# 多行方法
with open("data.txt", "r") as file:
    data = file.readline()
    print(data)  

# 单行方式
data = [line.strip() for line in open("data.txt","r")]
print(data)  

# 一行映射函数
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))

# 在一行代码中查找范围内的素数
print(list(filter(lambda a: all(a % b != 0 for b in range(2, a)),range(2,20))))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值