如何用函数的输出做一些事情,这是一个字典?

时间:2017-12-30 21:14:14

标签: python function dictionary

任何人都可以帮我解决以下问题吗? 我有一个返回字典的前一个函数。现在我需要这个函数来创建一个新函数,但我需要对字典做一些事情。为了向您展示我正在尝试做什么,dictionary(fasta_filename)是我以前的功能;

def test(fasta_filename, minMW, maxMW):
    interval = minMW, maxMW
    for key, value in dictionary(fasta_filename).items():
        if value in interval:
            print(key)
        else:
            print('intervals do not match')

这只是开始尝试我想要做的事情,但我遇到的主要问题是你可以用字典做的事情,比如.items(),如果你试图在功能。错误说:'NoneType' object has no attribute 'items'。我理解这个错误,因为当你执行function.items()时,你认为函数是字典,但事实并非如此。 我对这一切还很陌生,也许你可以说,但如果有人能给我一个暗示,我会很感激。 :)

1 个答案:

答案 0 :(得分:0)

您可以像这样修复测试,但它仍然只能打印出来。

修改function getAns(ans) { var ansGiven = document.getElementById("ansGiven").value; console.log(ans); console.log(ansGiven); if (ansGiven === ans) { document.getElementById("ansRes").innerHTML = "Correct!"; } else { document.getElementById("ansRes").innerHTML = "Try Again."; } ansGiven = ""; } 函数的return语句,检查def dictionary(fn) - dict的不同输出和包含数据的dict并进行检查。

None

输出(python 3.6):

def dictionary(fn):
    # you do stuff here with your file, make sure to NOT return None but 
    # always retunr at least an empty dict if your actions on your file 
    # do not result in a filled dictionary
    return {"dummy1" : 55, "dummy2" : 97, "dummy3" : 12345}
    # return None # uncomment this and comment the one above for a None-Dict

def test(fasta_filename, minMW, maxMW):
    interval = range(minMW, maxMW+1) # this is the interval [minMW..maxMW] including both
    dic = dictionary(fasta_filename)
    if not dic:
        print('dictionary is None')
        return None # leave test method

    for key, value in dic.items():
        if value in interval:
            print(key)
        else:
            print('intervals do not match for', key)

test("does not matter, dummy data provided internally",60,120)

intervals do not match for dummy1
dummy2
intervals do not match for dummy3

取决于dictionary is None 返回的内容。