你能用一个函数创建字典吗?

Can you create dictionaries with just a single function?

作为一个完全的初学者,我对这个功能感到非常自豪。虽然我相信可能有一种更简单、更 pythonic 的方式来做同样的事情:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)       
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)

上面的函数是一种相当复杂(我认为)的方法,可以将多个值(突变)放入键(基因)中。但是我想知道我是否可以调整它以便我可以通过这样做来获得字典:

dict(GenDict, Genes, Mutations)

print(GenDict)

我的问题是当我在函数中使用 dict 时,它不起作用:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)       
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)

由于未定义 GenDict,以上内容将无法使用。

我假设您希望 "Gen" 按其包含的数值存储。

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']
the_dict = {i:[] for i in Genes}

for i in Mutations:
    new_val = i.split(".")

   the_dict[new_val[0]].append(i)

print(the_dict)

输出:

{'Gen2': ['Gen2.A'], 'Gen3': ['Gen3.A', 'Gen3.B', 'Gen3.C'], 'Gen1': ['Gen1.A', 'Gen1.B']}

据我了解,您想从这里搬家:

gen_dict = make_dictionary(genes, mutations)

对此:

make_dictionary(gen_dict, genes, mutations)

其中 make_dictionary 函数 "creates" 变量 gen_dict.

不幸的是,变量并不是这样工作的。如果你想定义一个名为GenDict的变量,方法是使用GenDict = ...。你可以这样做:

gen_dict = {}
fill_dictionary(gen_dict, genes, mutations)

这将创建一个名为 gen_dict 的变量并将其分配给一个新的空字典。然后您的函数将通过并向该字典添加内容:

def fill_dictionary(d, genes, mutations):
    for g in genes:
      d[g] = [m for m in mutations if m.startswith(g)]

但是调用函数不会导致新变量出现在调用者的作用域中。 (这并不完全正确,因为 globals(),但对于大多数意图和目的而言,它是正确的。)

(顺便说一句,有一个单行代码可以创建字典:dictionary = { g : [m for m in mutations if m.startswith(g+".")] for g in genes }。在 Google 或 Whosebug 上搜索列表推导式和字典推导式——它们太棒了!)

我假设您具有 Python 以外的其他语言的编程背景;一种允许您更改函数参数的语言。好吧,Python 没有。问题不在于使用 dict,而在于您正在分配给函数参数这一事实。这不会在函数外产生影响。你想做的大概是这样的:

def fullDict(keys, values):
    return { key: [ value for value in values if key in value] for key in keys }

print(fullDict(Genes, Mutations))