【问题标题】:Approriate way of returning several lists in python function在python函数中返回多个列表的适当方法
【发布时间】:2021-01-28 13:02:13
【问题描述】:

我有一个函数:

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: 'function' 对象不可下标

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

有没有关于在函数中返回多个 python 列表的适当方式?

提前致谢

【问题讨论】:

  • 您可以使用 Visual Studio 代码等 Python 调试器查看返回值并检查潜在原因。

标签: python list function error-handling


【解决方案1】:

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

打电话时试试这个:

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

【讨论】:

  • 哦,这是一个错误,我没有意识到。它现在正在工作。非常感谢。 (我可以在5分钟内打出“接受标记”)
猜你喜欢
  • 2013-10-28
  • 1970-01-01
  • 2020-05-03
  • 2013-10-22
  • 2020-07-21
  • 2019-05-10
  • 1970-01-01
  • 2018-05-02
  • 2011-04-10
相关资源
最近更新 更多