轻松上手,快乐学习!

python 技巧让代码更好


一些小技巧可以让python的代码变得简洁
一、if 判断条件的简写 常规写法:
condition = True
if condidtion:
    x = 1
else:
    x = 0
print(x)
优化后:
condition = True
x = 1 if condition else 0;
print(x)
二、数据格式化
num1 = 10000000000
num2= 100000000
total = num1 + num2
print(total)
#结果是:10100000000
print(f'{total:,}')
#结果是:10,100,000,000
三、文件读取
常规
f = open('text.txt', 'r')
    file_contents = f.read()
f.close()words = file_contents.split(' ')
word_count = len(words)
print(word_count)
优化后
with open('text.txt', 'r') as f:
    file_contents = f.read()
words = file_contents.split(' ')
word_count = len(words)
print(word_count)
四、带序号的列表遍历
names = ['Rick', 'Jack', 'Sean', 'Summer']
index = 0
for name in names:
    print(index, name)
    index +=1

#运行结果
#0 Rick
#1 Jack
#2 Sean
#3 Summer
优化后:
names = ['Rick', 'Jack', 'Sean', 'Summer']
for index, name in enumerate(names, start=1):
    print(index, name)

# 打印结果
#1 Rick
#2 Jack
#3 Sean
#4 Summer

五、多列表之间的映射
names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']
heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']
for index, name in enumerate(names):
    hero = heroes[index]
    print(f'{name} is actually {hero}')

#运行结果
#Peter Parker is actually Spiderman
#Clark Kent is actually Superman
#Wade Wilson is actually Deadpool
#Bruce Wayne is actually Batman
优化:
names = ['Peter Parker', 'Clark Kent', 'Wade Wilson', 'Bruce Wayne']
heroes = ['Spiderman', 'Superman', 'Deadpool', 'Batman']
universes = ['Marvel', 'DC', 'Marvel', 'DC']
for index, name, universe in zip(names,heroes,universes):
    print(f'{name} is actually {hero} from {universe}')

#运行结果:
#Spiderman is actually Batman from Marvel
#Superman is actually Batman from DC
#Deadpool is actually Batman from Marvel
#Batman is actually Batman from DC