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

2024-04-26 05:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个初学者,我对这个函数感到非常自豪。尽管我相信可能有一种更简单、更像Python的方法来做同样的事情:

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)

由于性别没有定义,以上这些都是行不通的。你知道吗


Tags: keyforvaluekeysvaluesmutationsappendgenes
3条回答

据我所知,你想摆脱这一点:

gen_dict = make_dictionary(genes, mutations)

对此:

make_dictionary(gen_dict, genes, mutations)

其中make_dictionary函数“创建”变量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或StackOverflow上搜索列表理解和字典理解,它们太棒了!)你知道吗

我假设您希望“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']}

我假设您有使用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))

相关问题 更多 >