我想创建列表,但是在名为“ mydog.txt”的外部文件中具有列表的名称。
mydog.txt :
bingo
bango
smelly
wongo
这是我的代码,可将文本转换为列表元素。我认为它可以正常工作,但是由于某种原因,完成后无法保存这些值:
def createlist(nameoflist):
nameoflist = ["test"]
print(nameoflist)
file = open("mydog.txt")
for i in file.readlines():
i= i.replace("\n", "")
print(i) #making sure text is ready to be created into a list name
createlist(i)
file.close()
print("FOR fuction complete")
print(bingo) # I try to print this but it does not exist, yet it has been printed in the function
该子例程应该使用一个名称(例如“ bingo”),然后将其转换为列表,并在该列表中包含"test"
。
我应该拥有的最终变量是“ bingo = [” test“],bango = [” test“],smoryy = [” test“],wongo = [” test“]
最后应该打印的是['test']
,但该列表不存在。
为什么在子例程createlist
内部但不在子例程外部时,它作为列表打印出来?
答案 0 :(得分:0)
file = open("mydog.txt")
my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'
file.close()
或with
块不担心文件关闭
with open("mydog.txt") as file:
my_list =file.read().splitlines() # will create the list from the file which should contain only names without '\n'
如果要创建以文本文件中存在的名称命名的列表,则实际上应该创建一个dict
,其键为名称,值为包含字符串test
my_dict={i:['test'] for i in my_list}
然后尝试打印
print(my_dict['bingo']) # will print list ['test']
打印整个字典
print(my_dict)
输出:
{'bango': ['test'], 'bingo': ['test'], 'smelly': ['test'], 'wongo': ['test']}
答案 1 :(得分:0)
nameoflist
命名的变量,而不是它所引用的字符串。要解决这个问题,您必须分配给模块名称空间。实际上,这并不难:
def createlist(nameoflist):
globals()[nameoflist] = ["test"]
您必须问自己的问题是为什么要这么做。假设您加载了文件:
with open("mydog.txt") as f:
for line in f:
createlist(line.strip())
现在确实可以做到
>>> print(bingo)
['test']
但是,使用文件的重点是要具有动态名称。您不知道会用什么名字,一旦将它们放在全局名称空间中,就不会知道哪些变量来自文件,哪些变量来自其他地方。
请记住,全局名称空间只是一个花哨但常规的字典。我的建议是将变量保存在您自己的字典中,仅用于此目的:
with open("mydog.txt") as f:
mylists = {line.strip(): ['test'] for line in f}
现在您可以按名称访问项目了:
>>> mylists['bingo']
['test']
但更重要的是,您可以检查自己得到的名字,然后以有意义的方式对其进行实际操作:
>>> list(mylists.keys())
['bingo', 'bango', 'smelly', 'wongo']
答案 2 :(得分:0)
您可以使用exec
:
with open('mydog.txt') as f:
list_names = [line.strip() for line in f]
for name in list_names:
exec('{} = ["test"]'.format(name))
local = locals()
for name in list_names:
print ('list_name:', name, ', value:', local[name])
或
print (bingo, bango, smelly, wongo)
输出:
list_name: bingo , value: ['test']
list_name: bango , value: ['test']
list_name: smelly , value: ['test']
list_name: wongo , value: ['test']
or
['test'] ['test'] ['test'] ['test']