0

我想简化我的代码,尤其是避免使用方括号;所以我的问题是:

def someFunction():
    someString = "Hi!"
    someNumber = 22
    somePointer = ""
    someList = []

    names_list = ['someString','someNumber','somePointer','someList']
    val_list = [someString, someNumber, somePointer, someList]

    someDict = {}

    for i in range( len( names_list ) ) :
        someDict[names_list[i]] = val_list[i]  

    someOtherFunction( someDict )

def someOtherFunction( dict ):
    for key, value in dict.iteritems() :
        print key, value

    print someString, someNumber

someFunction()

有可能做到这样吗?

4

3 回答 3

1

如果我理解正确,您需要一个将变量名称与值相关联的字典。我建议您建立一个包含名称的列表和一个包含值的列表。然后,您将项目附加到您的字典中。

someString = "Hi!"
someNumber = 22
somePointer = 4
someList = []

names_list = ['someString','someNumber','somePointer','someList']
val_list = [someString, someNumber, somePointer, someList]
len_list = len(val_list)

someDict = {}

for i in range(len_list) :
    someDict[names_list[i]] = val_list[i]  

然后,您可以查询您的 dict 正在做的事情,比如说

>>> someDict['someString']
'Hi!'
于 2013-05-17T05:59:53.293 回答
1

如果您知道变量列表并且它们将在某些函数中使用,则无法理解为什么这会很有用

# generate names and values again at other place
def foo():
    for d in someDict :
        d_name = d

然后你可以在函数调用期间解压它们

def foo(someString=None,
        someNumber=None,
        somePointer=None,
        someList=None):
    pass

foo(**someDict)
于 2013-05-17T06:22:15.967 回答
0

我发现最简单的方法是使用 dict() 内置构造函数:

someString = "Hi!"
someNumber = 22
somePointer = ""
someList = []

someDict = dict( 
    string = someString, number = someNumber,
    pointer = somePointer, list = someList )

print someDict

Output : { "string" : "Hi", "number" : 22, "pointer" : "", "list" : [] }
于 2013-06-01T13:14:55.727 回答