首页 > 解决方案 > 在python函数中返回多个列表的适当方法

问题描述

我有一个功能:

def extract_embedding_word2vec(y_text, w_e):
    
    n_run = len(y_text)    
    y_e = []
    false_index = []
    sentence_index = []
    
    for i in range(n_run):
        word2vec_run = []
        false_index_this_run = []
        sentence_index_this_run = []
        for j in range(len(y_text[i])):    
            if(len(y_text[i][j]) == 1):
                sentence_index_this_run.append(1)
                try:
                    word2vec_run.append(word2vec_model.wv[y_text[i][j][0].lower()])
                    false_index_this_run.append(1)
                except:
                    word2vec_run.append(word2vec_model.wv["lol"]) #fixme, until here
                    #print(y_text[i][j])
                    not_included_words.add(y_text[i][j][0].lower())
                    false_index_this_run.append(0)
                    #print("not included: %s" %y_text[i][j])
            else:
                sentence_index_this_run.append(0)
                
            
        
        y_e.append(word2vec_run)
        false_index.append(false_index_this_run)
        sentence_index.append(sentence_index_this_run)
    
    
    # Output format: list of n_run ta, each element: n_stim * n_dim_of_embedding

    print(len(y_e[0][0]))
    return (y_e, false_index, sentence_index)

还:

def join_list(list2d):
    
    new_list = []
    
    for i in range(len(list2d)):
        for j in range(len(list2d[i])):
            new_list.append(list2d[i][j])
            
    return (new_list)

然后,稍后,我这样调用这个函数:

y_e, false_index, sentence_index = extract_embedding_word2vec(y_t, w_e)
y_joined = join_list(y_sep)
f_joined = join_list[flag_sep]
s_joined = join_list[sen_sep]

它适用于“y_joined”,但对于 f_joined 我收到以下错误:

TypeError:“函数”对象不可下标

在其他一些线程中,我发现这个错误可能是由于我们在某处定义了例如“flag_sep”作为函数......但我在我的代码中搜索并意识到没有新的定义/使用这个变量。

是否有关于在函数中返回多个 python 列表的适当方法?

提前致谢

标签: pythonlistfunctionerror-handling

解决方案


您有括号类型的错字。你()不需要[][]用于对可迭代对象进行索引。

打电话时试试这个:

f_joined = join_list(flag_sep)
s_joined = join_list(sen_sep)

推荐阅读