其他
迭代列表不要For循环,这是Python列表推导式最基本的概念
(给Python开发者加星标,提升Python技能)
转自:机器之心,英文:Benedikt Droste
# Creating our animal park
animal_park = ['Rabbit','Rabbit','Rabbit','Rabbit','Cat','Cat','Cat','Cat','Cat','Cat','Cat', 'Turtle','Turtle','Turtle','Turtle','Turtle','Turtle','Turtle', 'Dog','Dog', 'Kangaroo','Kangaroo','Kangaroo','Kangaroo','Kangaroo','Kangaroo']
# Creating a new list for our animal doctor with all animals
animal_doctor = []
for animal in animal_park:
animal_doctor.append(animal)
animal_doctor = [animal for animal in animal_park]
图1:标准循环与列表推导的对比。
animal_doctor = []
for animal in animal_park:
if animal != 'Dog' and animal != 'Cat':
animal_doctor.append(animal)
nimal_doctor = [animal for animal in animal_park if animal != 'Dog' and animal != 'Cat']
图2:列表推导与标准循环二者速度的对比。
推荐阅读
(点击标题可跳转阅读)
TensorFlow与PyTorch之争,哪个框架最适合深度学习
Python 2 倒计时!官网提醒尽早升级到 Python 3
觉得本文对你有帮助?请分享给更多人
关注「Python开发者」加星标,提升Python技能
好文章,我在看❤️