返回函数外部时出错,但打印工作正常

2024-06-16 15:53:55 发布

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

下面是我的代码。我想在其他函数中使用finalList,因此我尝试返回finalList,但在函数外得到一个错误'return'。
如果我使用print finalList,它可以很好地打印结果。你知道吗

你知道怎么做吗?你知道吗

import csv   
from featureVector import getStopWordList  
from preprocess import processTweet  
from featureVector import getFeatureVector  

inpTweets = csv.reader(open('sampleTweets.csv', 'rb'), delimiter=',', quotechar='|')  
stopWords = getStopWordList('stopwords.txt')   
featureList = []   
tweets = []   
for row in inpTweets: 
    sentiment = row[0]   
    tweet = row[1]  
    processedTweet = processTweet(tweet)  
    featureVector = getFeatureVector(processedTweet)  
    featureList.extend(featureVector)
    tweets.append((featureVector, sentiment));

finalList = list(set(featureList))

Tags: csv函数fromimporttweetstweetrowsentiment
1条回答
网友
1楼 · 发布于 2024-06-16 15:53:55

I want to use the finalList in some other function

你已经可以这么做了。你知道吗

# other code...
finalList = list(set(featureList))  # this is global

def foo():
    print(finalList)

foo()

'return' outside function

如果您想return finalList,那么为它创建一个函数。你知道吗

def getFinalList():
    # other code...
    return list(set(featureList)) 

方案1

def foo():
    final_list = getFinalList()
    print(final_list)

foo()

方案2

def foo(final_list):
    print(final_list)

foo(getFinalList())

相关问题 更多 >