我目前正试图通过一个变量从文件中导入一个变量,然后尝试将该值与输入值进行比较。 但在运行脚本时,我遇到了以下错误:
TypeError: argument of type 'module' is not iterable
这是我尝试导入的文件中的列表:
var1 = ['cookies','pretzels']
这是我的代码:
usri = input('what is your favorite pastry')
#compare count is a counter with for example the value 1. The counter then joins the var.
#My idea is that var1 will be the variable which is being imported.
allowlist = str('var{}'.format(compare_count))
#Now I am trying to import var1 from my_file
allowlist = __import__('my_file'.format(allowlist))
#after var1 is imported from my_file I want to check if the user input is an item of var1
if usri in allowlist:
print('user input was found')
else:
print('user input wasn't found')
#In this example var1 is the only variable in the file I try to import but in the main code there are a lot of other variables.
我做错什么了吗?如果是这样的话,如果有人能告诉我我做错了什么并帮助我解决这个问题,我会非常高兴:)
提前感谢您的帮助和建议:)
演示如何使用导入。创建要从中导入的python文件,如
my_file.py
:然后,您可以像这样在其他代码中导入它:
然后allowlist将是列表
["a", "b", "c"]
,您可以将其用作列表相关问题 更多 >
编程相关推荐