清理方法来检查变量所在的列表中的哪个列表

时间:2017-08-30 11:21:04

标签: python list loops contains

我想在20多个列表中查看变量bases所在的列表。我当前的解决方案有效,但它笨拙而且凌乱:

bases = "aau"    

ala = ["gca","gcu","gcg","gcc"]
arg = ["agg","aga","cgg","cga","cgc","cgu"]
asn = ["aau","aac"]
# etc - tons of arrays

if bases in ala:
    return "Alanin"
if bases in arg:
    return "Arginin"
if bases in asn:
    return "Asparagin"
# etc - tons of checks

总的来说,对于所有列表和所有检查,此功能为69行。我该如何清理它?

1 个答案:

答案 0 :(得分:3)

您可以使用"映射"您定义的列表的名称。然后你可以简单地遍历那个词典:

bases = "aau"

dct = {"Alanin": ["gca","gcu","gcg","gcc"],
       "Arginin": ["agg","aga","cgg","cga","cgc","cgu"],
       "Asparagin": ["aau","aac"]}

for name, lst in dct.items():
    if bases in lst:
        return name