如何将列表中对象的变量名转为字符串并打印?
如何在嵌套循环中打印顶层列表的变量名字符串
我明白你的问题啦——你想在嵌套循环里打印出urls1和urls2这两个变量名的字符串,但之前的方法都没成功,对吧?
问题核心分析
当你把urls1和urls2放进urllist时,urllist里存储的是这两个列表对象本身的引用,而不是它们的变量名。Python不会自动记录变量名和对象的对应关系,所以直接从循环里的i(也就是列表对象)没法反向拿到它的变量名。
你之前尝试的enumerate方法之所以不行,是因为i[idx]里的i是urls1/urls2列表,idx是0或1,取的是列表里的第0/1个URL元素,自然打印的是URL而非变量名。
解决方案
方案1:使用字典存储名称与列表的映射(推荐)
这是最符合Python设计思路的方式,用字典的键保存你想要的名称字符串,值对应列表对象:
urls1 = ["https://stackoverflow.com/questions/61441230/typeerror-list-indices-must-be-integers-or-slices-not-list", "https://docs.python.org/2.3/whatsnew/section-enumerate.html", "https://docs.python.org/3/tutorial/introduction.html#lists"] urls2 = ["https://stackoverflow.com/questions/6340351/iterating-through-list-of-list-in-python", "https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists"] # 用字典替代原有的urllist,键是变量名字符串,值是对应的列表 url_dict = {"urls1": urls1, "urls2": urls2} container = [] for name, url_list in url_dict.items(): for u in url_list: filename = u.split('/')[-1] # 保留你的原有逻辑 print(name) # 这里会打印"urls1"或"urls2" container.append(name)
方案2:使用元组列表存储名称与列表
如果你更习惯用列表结构,可以把每个元素改成包含名称和列表的元组:
urls1 = ["https://stackoverflow.com/questions/61441230/typeerror-list-indices-must-be-integers-or-slices-not-list", "https://docs.python.org/2.3/whatsnew/section-enumerate.html", "https://docs.python.org/3/tutorial/introduction.html#lists"] urls2 = ["https://stackoverflow.com/questions/6340351/iterating-through-list-of-list-in-python", "https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists"] # 每个元素是(名称字符串, 列表对象)的元组 urllist = [("urls1", urls1), ("urls2", urls2)] container = [] for name, url_list in urllist: for u in url_list: filename = u.split('/')[-1] print(name) container.append(name)
为什么不推荐反向查找变量名?
你可能会想通过遍历全局/局部变量来查找对象对应的变量名,但这种方法非常不可靠:比如如果有多个变量指向同一个列表对象,你会拿到多个名称;而且代码的健壮性很差,一旦变量名修改或者环境变化就会出错。所以上面两种显式存储关联关系的方法才是最佳实践。
内容的提问来源于stack exchange,提问作者cmoez
相关产品推荐
相关产品推荐

