Python:返回外部函数

2024-10-02 16:30:33 发布

您现在位置:Python中文网/ 问答频道 /正文

for x in non_neutral.collect():
tweet = str(x[2])
sid = x[1]
status = x[0]
text = word_tokenize(tweet)
text1 = list(text)
tweet = x[2].split()
pronoun = intersect(second_pronoun,tweet)
perojective = intersect(less_offensive,tweet)
if pronoun:
    pronoun_index = tweet.index(pronoun[0])
    pero_index = tweet.index(perojective[0])
if pero_index <= pronoun_index+3:
    status = 1
    return Row(status=status,tid=sid,tweet = str(tweet))
else:
    status = 0
    return Row(status=status,tid=sid,tweet = str(tweet))

对于这个特定的代码片段,我经常会遇到这个错误,我不明白为什么

^{pr2}$

我又试着写了一遍代码,但还是犯了同样的错误。在


Tags: 代码textindexreturnifstatustweetrow
3条回答

我在代码片段中没有看到关键字def,它表示函数定义的开始。代码片段是否取自函数体?在

以下是for循环中返回的工作示例:

from random import shuffle

def loop_return():
    values = [0,1]
    shuffle(values)
    for i in values:
        if i == 0:
            return 'Zero first.'
        if i == 1:
            return 'One first.'

你的程序实际上并不包含函数。Return语句必须包含在函数中,在本例中您没有定义任何语句。在

请尝试以下类似的方法(请注意,这并不包括您的所有代码,这只是一个示例):

def Foo():
    #Here is where you put all of your code
    #Since it is now in a function a value can be returned from it
    if pronoun:
        pronoun_index = tweet.index(pronoun[0])
        pero_index = tweet.index(perojective[0])
    if pero_index <= pronoun_index+3:
        status = 1
        return Row(status=status,tid=sid,tweet = str(tweet))
    else:
        status = 0
        return Row(status=status,tid=sid,tweet = str(tweet))

Foo()

只要你把你的代码放在一个函数里,它就会工作。python中基本函数定义的语法是:def Foo(Bar):,其中Foo是函数的名称,Bar是您可能需要的任何参数,每个参数都用逗号分隔。在

你实际上没有函数,所以你不能返回任何东西。你可以通过把代码变成一个过程来修复它。在

相关问题 更多 >