Python优化:如何避免for循环与range的结合使用?
如何避免使用for循环结合range的非Pythonic写法?
我编写了一个输入函数,用于从指定数量的产品中选择产品并进行错误处理。目前我使用了for i in range(no_of_products_sel)的写法,这种方式不够Pythonic,应该可以不借助range实现迭代,但我未能成功。以下是我的部分代码:
valid_expression = False # for next while loop while valid_expression is False: products = [] for i in range(no_of_products_sel): products_confirmed = False # for next while loop while products_confirmed is False: product = input(f"Please enter product name {i+1}:") if product.lower().strip() == "exit": print("See you soon!") return None product_clean = product.lower().title().strip() if product_clean in products: print(f"Already chosen! Choose another product!") elif product_clean in list_of_products: products.append(product_clean) products_codes[product_clean]=product_codes(product) # get product codes, save them in dict product_confirmed = True # 注意:原代码此处变量名拼写错误,应为products_confirmed elif product_clean not in list_of_products: print(f"\n---\nYou have entered '{product}', which is not in the stock. Enter another product!\n---\n") valid_expression = True
解决方案:用while循环基于列表长度判断,替代range循环
核心思路是:我们的目标是收集指定数量的有效产品,而非单纯执行N次循环。直接通过判断products列表的长度来控制迭代,既贴合业务逻辑,又避免了冗余的索引变量,更符合Pythonic风格。
修改后的代码示例:
valid_expression = False while not valid_expression: products = [] # 只要收集的产品数量未达要求,就继续循环 while len(products) < no_of_products_sel: products_confirmed = False # 用已选产品数量+1来提示用户当前是第几个输入项 product_num = len(products) + 1 while not products_confirmed: product = input(f"Please enter product name {product_num}:") if product.lower().strip() == "exit": print("See you soon!") return None product_clean = product.lower().title().strip() if product_clean in products: print(f"Already chosen! Choose another product!") elif product_clean in list_of_products: products.append(product_clean) products_codes[product_clean] = product_codes(product) products_confirmed = True # 修正原代码的变量名拼写错误 else: print(f"\n---\nYou have entered '{product}', which is not in the stock. Enter another product!\n---\n") valid_expression = True
为什么这样更Pythonic?
- 关注点从“循环次数”转移到“业务目标(收集足够产品)”,代码可读性更强
- 无需维护额外的索引变量
i,减少冗余代码 - 逻辑更直观:只要没收集够指定数量,就继续请求输入
内容的提问来源于stack exchange,提问作者Martha's Vineyard
相关产品推荐
相关产品推荐

