良好的编码风格:使用临时变量列表长度与否?

 滑膛 发布于 2023-02-09 09:57

这个问题与python有关,但它实际上对很多语言都很常见.看看那段代码:

import sys
people = ['John', 'Jack', 'Charles']
cities = ['London', 'Liverpool', 'Manchester']
if (len(cities) != len(people)):
    print "Error! Length of cities list \
    (%s) differs from length of people list (%s)" % (len(cities), len(people))
    sys.exit(1)
for i in xrange (len(cities)):
    print "Hello, %s from %s" %(people[i], cities[i])

似乎是对的.但是在这个小片段len被称为3到5次(如果列表长度相等则为3次,如果列表长度不同则为5次).我们需要重写这样的代码吗?

import sys
people = ['John', 'Jack', 'Charles']
cities = ['London', 'Liverpool', 'Manchester']
people_count = len(people)
cities_count = len(cities)
if (cities_count != people_count):
    print "Error! Length of cities list \
    (%s) differs from length of people list (%s)" % (cities_count, people_count)
    sys.exit(1)
for i in xrange (cities_count):
    print "Hello, %s from %s" % (people[i], cities[i])

换句话说:在哪些情况下我们需要临时变量来存储列表长度,在哪些情况下不需要它?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有