如何将带有字符串元素且不带引号的python列表转换为正确的列表?
考虑以下列表: list1 = [home , school, ground, field] 列表1=[家、学校、场地、场地] 正如您所看到的,list的元素是没有引号的字符串,因此这是一个无效的list。有没有办法使用python将此列表转换为正确的列表?如何将带有字符串元素且不带引号的python列表转换为正确的列表?,python,string,list,Python,String,List,考虑以下列表: list1 = [home , school, ground, field] 列表1=[家、学校、场地、场地] 正如您所看到的,list的元素是没有引号的字符串,因此这是一个无效的list。有没有办法使用python将此列表转换为正确的列表? 列表应如下所示: list1 = ['home' , 'school', 'ground', 'field'] done = False while not done: try: list1 = [home , sc
列表应如下所示: list1 = ['home' , 'school', 'ground', 'field']
done = False
while not done:
try:
list1 = [home , school, ground, field]
except NameError as e:
varname = str(e).split("'")[1]
locals()[varname] = varname
else:
done = True
print(list1)
# ['home', 'school', 'ground', 'field']
列表1=['home'、'school'、'ground'、'field']是的,从技术上讲,你可以这样做: list1 = ['home' , 'school', 'ground', 'field']
done = False
while not done:
try:
list1 = [home , school, ground, field]
except NameError as e:
varname = str(e).split("'")[1]
locals()[varname] = varname
else:
done = True
print(list1)
# ['home', 'school', 'ground', 'field']
但我不推荐
也许您可以编写一个decorator,将每个namererror
转换为一个变量,并重新运行代码运行的任何范围,希望是一个函数。。。但老实说。。。你只会把你的代码变成一个无法维护的,复杂的混乱
还有,这段代码首先是如何编写的?除非您的脚本是由其他程序生成的模板。。。在这种情况下,为什么不正确生成它们P除非是变量名。这不是有效的代码。如果您确实有一个列表
list1=[home,school,ground,field]
,您只需尝试运行代码就会得到namererror
。list1=[home,school,ground,field]来自哪里?您是从文本文件还是标准输入读取它?正如其他人所说,行在Python脚本中无效,除非home
,school
等是已经存在的变量。如果它是“[home,school,ground,field]”
,那么您可以使用拆分(“,”)
来获取有效列表我知道代码会给出错误,我只是想知道是否有任何方法或模块可以将list1转换为合适的python列表。谢谢你。邪恶,但可爱使用这种方法的后果是什么