如何让Python循环中的整数变量e跨输入行持续递增?
实现跨输入行的连续索引生成
需求说明
每次输入新行时,整数索引从0开始持续递增,生成格式为ItemListData(索引)=(ItemDefination=输入内容")的输出。
输入示例:
example1 example2
原代码
def no(paths: str): e = 0 for path in paths.split(" "): print(" ItemListData(" + str(e) + ")=(ItemDefination=" + path + '")') e = e + 1 while True: paths = input() no(paths)
当前输出
ItemListData(0)=(ItemDefination=example1") ItemListData(0)=(ItemDefination=example2")
期望输出
ItemListData(0)=(ItemDefination=example1") ItemListData(1)=(ItemDefination=example2")
问题根源
每次调用no()函数时,内部变量e都会被重置为0,无法实现跨输入行的索引持续累加。
解决方案
以下是几种可行的修改方式:
方法1:使用全局变量
将索引变量e定义在函数外部,函数内部通过global关键字引用并更新它:
e = 0 def no(paths: str): global e for path in paths.split(" "): print(" ItemListData(" + str(e) + ")=(ItemDefination=" + path + '")') e += 1 while True: paths = input() no(paths)
方法2:索引作为参数传递并返回更新后的值
在循环中维护索引变量,每次调用函数时传入当前索引,函数处理完成后返回新的索引:
def no(paths: str, current_e): e = current_e for path in paths.split(" "): print(" ItemListData(" + str(e) + ")=(ItemDefination=" + path + '")') e += 1 return e e = 0 while True: paths = input() e = no(paths, e)
方法3:使用闭包封装索引
通过闭包隐藏索引变量,避免全局变量的使用:
def create_index_tracker(): e = 0 def tracker(paths: str): nonlocal e for path in paths.split(" "): print(" ItemListData(" + str(e) + ")=(ItemDefination=" + path + '")') e += 1 return tracker no = create_index_tracker() while True: paths = input() no(paths)
内容的提问来源于stack exchange,提问作者DrewsDoggo
相关产品推荐
相关产品推荐

