如何从另一个模块调用用户定义的变量…:P
我想为x分配一个变量,在这种情况下,列表。
a = ['a','b','c']
b = ['d','e','f'] ##列表a和b都在一个单独的
x = a
打印(importedModule.x)
当我以这种方式运行它时,该程序只是在主要模块中仍未定义X,因此这是Psuedocode ...有什么想法吗?
我还想知道是否可以使用相同的解决方案来调用从导入的模块而不是简单变量的随机/用户定义的函数。
" A"和" X"都指向同一对象,因此没有区别,即使用" A"。
- A = ['a', 'b', 'c']
- x = A
- print id(A)
- print id(x)
- x[1] = "1"
- print A
对我来说很好,所以发布您的代码。
自己尝试一下,看看。
@dwblas
-----------------------------------------------------------------------------
导入ListModule
x =输入('类型A,B或C')## A,B或C是在导入模块中存储的列表
打印(ListModule.x)
当以这种方式运行时,导入列表及其列表名称时,我会发现一个错误,说X未定义。
>>>
A型A,B或C.A
Trackback(最近的最新电话):
文件" c:/users/untral帐户/桌面/bbpowre3vrjh",第5行,in
打印(ListModule.x)
attributeError:"模块"对象没有属性'x'
>>>
对不起,我确实写了第一个示例。
作为用户输入的" A"是一个字符串,与变量完全不同的内存块中,a"在ListModule中。
- ##---------- listModule ----------
- A = ["a", "c", "b"]
- B = "ABC"
- C = 123
- ##---------- calling program ----------
- import listModule
- x = input('Type A, B, or C--> ')
- x = x.upper()
- if "A" == x: ## note the comparison...string==x
- print(listModule.A) ## not a string (in quotes), but a variable
- elif "B" == x:
- print(listModule.B)
- elif "C" == x:
- print(listModule.C)
- # if you have a lot of comparisons you can use a list or tuple or dictionary
- print("----- second way")
- for check_it in (("A", listModule.A), ("B", listModule.B), ("C", listModule.C)):
- if x = check_it[0]:
- print(check_it[1])
@dwblas
-----------------------------------------------------------------------
我知道如何从导入的模块调用设定的函数或变量。...我不知道该怎么做是
紧凑地允许用户从导入的模块访问超过10,000(是........一万...)列表(实际上是几个模块:P)。我需要写10k Elif块。
我不能简单地写出每个Elif块。
好吧...我可以,但是我真的没有效果。大声笑:d
此外,这只是一个不切实际的文件。
我希望这可能具有最低的足迹。
是否没有办法将两者进入相同的内存块?
否。无法自动将键盘输入映射到内存中的变量。您必须自己编程,因为这正在编程计算机。您可以使用字典来简化事物。一个例子如下。
- ##---------- listModule ----------
- external_dict = {"A":["a", "b", "c"],
- "B":["B", "B", "b"],
- "C":[1, 2, 3] }
- ##---------- calling program ----------
- import listModule
- x = input('Type A, B, or C--> ')
- x = x.upper()
- if x in listModule.external_dict:
- print(listModule.external_dict[x])
- # or
- choices_dict = {"A":listModule.A,
- " B":listModule.B } ## etc but that would require thousands of hand built entries
几乎不可能在黑暗中以良好的选择射击。列表是否以任何方便的方式命名,可以自动放入字典中?您可以对列表模块进行编程以生成列表的生成列表吗?您能本身迭代程序的陈述并将列表提取到字典中吗?
@dwblas
------------------------------------------------------------------------------------ - -
哇。。哈哈
这就解释了为什么在"解决"中带有10K问题的紧凑型测试引擎并不常见。 :P感谢您 r帮助。
- import re
- f = open('data.txt', 'r')
- data = {}
- for line in f:
- key, value = re.findall('([^=]+)=(.*)', line)[0]
- data[key.strip()] = eval(value.strip())
- f.close()
- ## from here, you can save the dictionary with pickle,
- ## ready to be loaded and quickly accessed
- x = raw_input('Type A, B, or C--> ')
- print data[x.upper()][1] # returns 'e' if x == 'b'
- del data
避免使用eval()。
标签: python