【发布时间】:2017-06-08 16:16:37
【问题描述】:
作为一个初学者,我为这个功能感到非常自豪。虽然我相信可能有一种更简单、更 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,因此上述方法不起作用。
【问题讨论】:
-
你想要的输出是什么?
-
一个字典,其中基因是键,突变是每个键的值。所以 Gen1 有 ['Gen1.A', 'Gen1.B'] 作为值等等。
-
为什么你想让你的函数看起来像
fullDict(GenDict, Genes, Mutations)而不是GenDict = fullDict(Genes, Mutations)?这似乎很奇怪。 -
@MiguelAlberolaCano 对于代码风格,您是否有想要改进的工作代码?我认为这不是主题,但您可能需要考虑codereview.stackexchange.com
-
没有考虑,但是谢谢!
标签: python python-3.x dictionary key python-3.6