如何通过变量中存储的名称访问Python列表?
问题原因
你现在的代码里,curfile是字符串类型的"thislist",所以curfile[0]取的是这个字符串的第一个字符't',自然拿不到列表的元素。
解决方法
方法1:通过全局/局部命名空间字典访问
Python的全局变量存在globals()字典中,键是变量名的字符串,值是变量本身。你可以这样修改:
thislist = ["apple", "banana", "cherry"] curfile = "thislist" print(globals()[curfile][0]) # 输出 apple
如果变量是局部作用域的,用locals()代替globals()即可。
方法2:用字典映射(更推荐)
直接用字典把列表名和对应的列表关联起来,这种方式更安全可控,不会意外访问到其他全局变量:
# 先定义所有需要的列表映射 list_map = { "thislist": ["apple", "banana", "cherry"], # 可以添加更多列表 "otherlist": ["orange", "grape"] } curfile = "thislist" print(list_map[curfile][0]) # 输出 apple
内容的提问来源于stack exchange,提问作者Irukulla Avikshith
相关产品推荐
相关产品推荐

