如何从我 运行 循环的函数中定义变量?

How to define variable from function that I'm running loop over?

这可能是一个超级幼稚的问题,但我有一个函数,我试图将列表中的每个项目作为输入进行循环。函数是get_t1_file()

def get_bids_nifti(acq):
    bids_niftis = [f for f in acq.files if ('info' in f.keys() and 'BIDS' in f.info.keys() and "nii" in f.name)]
    if len(bids_niftis) > 0:
        return(bids_niftis.pop())
    else:
        return(None) 
    
def get_t1_file(sess):
    '''
        Function to pick the most desirable T1 file out of several in a session.
    '''
    #is_t1 = [any(['T1' in f.classification['Measurement'] for f in a.files \
    #    if 'Measurement' in f.classification.keys()]) for a in sess.acquisitions()]
    #t1_acq = [a for (a, v) in zip(sess.acquisitions(), is_t1) if v]
    
    t1_acq = []
    acqlist = sess.acquisitions()
    for acq in acqlist:
        if any(['T1' in f.classification['Measurement'] for f in acq.files \
            if 'Measurement' in f.classification.keys()]):
                t1_acq.append(acq)
    
    t1_file = None
    
    for acq in t1_acq:
        lab = acq.label.lower()
        if ("vnav" in lab) and ("moco" in lab) and ("rms" in lab) and not ("nd" in lab):
            t1_file = get_bids_nifti(acq)
            return(t1_file)
    
    for acq in t1_acq:
        lab = acq.label.lower()
        if ("vnav" in lab) and ("rms" in lab) and not ("nd" in lab):
            t1_file = get_bids_nifti(acq)
            return(t1_file)
    
    for acq in t1_acq:
        lab = acq.label.lower()
        if ("ax" in lab) and ("mprage" in lab):
            t1_file = get_bids_nifti(acq)
            return(t1_file)
    
    for acq in t1_acq:
        lab = acq.label.lower()
        if ("sag" in lab) and ("mprage" in lab):
            t1_file = get_bids_nifti(acq)
            return(t1_file)
    
    return(t1_file)

我的循环 运行 列表中项目的函数是:

t1_files = []
for s in session_ids:
    sess = fw.get(s)
    get_t1_file(sess)
    t1_files.append(t1_file)

但是我有一个错误,返回的变量没有定义。我的循环或函数中是否缺少某些东西来确保 t1_file 已定义?

Traceback (most recent call last):

  File "<ipython-input-16-b85e5ebfcdb1>", line 5, in <module>
    t1_files.append(t1_file)

NameError: name 't1_file' is not defined

您必须使用函数的返回值:

t1_files = []
for s in session_ids:
    sess = fw.get(s)
    t1_files.append(get_t1_file(sess))