这篇博客将介绍20个Python一行代码。这些单行代码将节省时间,并使代码看起来更清晰、更易读。
# 20个有趣的单行python代码
# one_line.py
# 1. 单行for循环
mylist = [200, 300, 400, 500]
# 单行循环
result = []
for x in mylist:
if x > 250:
result.append(x)
print(result) # [300, 400, 500]
# 一行代码方式
result = [x for x in mylist if x > 250]
print(result) # [300, 400, 500]
# 2. 单行while循环
# Method 1 单个语句
# while True: print(1) # infinite 1
# Method 2 多个语句
x = 0
while x < 5: print(x); x = x + 1 # 0 1 2 3 4 5
# 3. 单行IF else语句
# 要在一行中编写 IF Else 语句,我们将使用三元运算符。三元的语法是“[on true] if [expression] else [on false]”。
# Example 1 if else
print("Yes") if 8 > 9 else print("No") # No
# Example 2 if elif else
E = 2
print("High") if E == 5 else print("数据工作室") if E == 2 else print("Low") # Data STUDIO
# Example 3 only if
if 3 > 2: print('完全正确') # 完全正确
# 4. 单行合并词典
d1 = {'A': 1, 'B': 2}
d2 = {'C': 3, 'D': 4}
# Method1
d1.update(d2)
print(d1) # { 'A': 1, 'B': 2, 'C': 3, 'D': 4}
# Method2
d3 = {**d1, **d2}
print(d3) # {'A': 1, ' B':2,'C':3,'D':4}
# 5. 单行函数:三元运算符或者lambda函数
# Function in one line
# Method1
def fun(x): return True if x % 2 == 0 else False
print(fun(2)) # False
# Method2
fun = lambda x: x % 2 == 0
print(fun(2)) # 真
print(fun(3)) # 假
# 6. 单行递归
# Fibonaci 单行递归示例
def Fib(x): return 1 if x in {0, 1} else Fib(x - 1) + Fib(x - 2)
print(Fib(5)) # 8
print(Fib(15)) # 987
# 7.在一行中过滤数组
mylist = [2, 3, 5, 8, 9, 12, 13, 15]
# Normal way
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]
# 8. 单行异常处理
try:
print(x1)
except:
print("Error")
# Single line way
exec('try:print(x) \nexcept:print("Error")') # Error
# 9. 单行数组转dict
# Dictionary in one line
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}
# 10. 多变量单行赋值
x = 5
y = 7
z = 10
print(x, y, z) # 5 7 10
# Single line way
a, b, c = 5, 7, 10
print(a, b, c) # 5 7 10
# 11. 单行交换值
v1 = 100
v2 = 200
temp = v1
v1 = v2
v2 = temp
print(v1, v2) # 200 100
# One-line value swapping
v1, v2 = v2, v1
print(v1, v2) # 200 100
# 12. 单行排序
mylist = [32, 22, 11, 4, 6, 8, 12]
# Method1
mylist.sort()
print(mylist) # # [4, 6, 8, 11, 12, 22, 32]
print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]
# 13. 单行读文件
try:
with open("log_demo.py", "r") as file:
data = file.readline()
print(data) # Hello world
# Single line way
data = [line.strip() for line in open("log_demo.py", "r")]
print(data) # ['hello world', 'Hello Python']
except:
print('error')
# 14. 单行类
class Emp:
def __init__(self, name, age):
self.name = name
self.age = age
emp1 = Emp("a44", 22)
print(emp1.name, emp1.age) #
# Single line way
# Method 1 Lambda with Dynamic Attributes
Emp = lambda: None;
Emp.name = "a44";
Emp.age = 22
print(Emp.name, Emp.age)
# Method 2
from collections import namedtuple
Emp = namedtuple('Emp', ["name", "age"])("a44", 22)
print(Emp.name, Emp.age)
# 15.单行分号
a = "Python";b = "编程";c = "语言";print(a, b, c)
# Python 编程语言
# 16.单行print
for x in range(1, 5):
print(x) # 1 2 3 4
# Single line way
print(*range(1, 5)) # 1 2 3 4
print(*range(1, 6)) # 1 2 3 4 5
# 17.单行map
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))
# [7, 8, 9, 10, 11, 12]
# 18.单行代码:del删除列表多个元素
mylist = [100, 200, 300, 400, 500]
del mylist[1:: 2]
print(mylist) # [100, 300, 500]
# 19. 单行打印图案 print+* 实现多次相同的打印
print('') # print #
# Single line way
print('' * 3) # print ( ' ' * 2 ) # 打印( '' * 1 ) #
# 20. 单行代码找到一个数范围内的素数
print(list(filter(lambda a: all(a % b != 0 for b in range(2, a)),
range(2, 20))))
# [2, 3, 5, 7, 11, 13, 17, 19]